2017-07-26 72 views
-1

我想在Javascript中使用它的id來禁用鏈接。默認情況下,它是不可見的,如下所示。當特定的ID來自後端時,我將啓用鏈接。如何使用css禁用按鈕

HTML

<li id="viewroleId" style="display: none;"> 
    <a href="viewrole"><spring:message code="label.viewrole" /></a> 
</li> 

的Javascript: -

if (key == 1) { 
    var id = value; 
    var div = document.getElementById(id); 

    if(div != null){ 
     if (div.style.display == 'none' || div.style.display == '') { 
      // Here it will display the link 
      div.style.display = 'block'; 
     } 
    } 
} 

在上面的Javascript代碼,我將顯示鏈接,但我想,以顯示和禁用鏈接。我怎樣才能禁用與CSS的鏈接呢?

+5

查看[ngDisabled](https://docs.angularjs.org/api/ng/directive/ngDisabled)。 – Kevin

+1

爲什麼不添加作爲屬性禁用? - 也作爲建議 - 從不做內聯css或js - 這是不好的做法,導致難以維護的代碼 – ThisGuyHasTwoThumbs

+0

如果我保持ng禁用,那麼我需要爲每個禁用的href提供不同的名稱。現在,ID來自數據庫,因此我可以使用它的ID進行顯示。 – Murali

回答

-1

首先,在CSS

.disabled { 
    display: block !important; /* since you set the element's display to none inline, 
            we need to use !important flag (which is pretty bad) 
            to override the inline style */ 
    pointer-events: none; /* Disable an element interaction, so it will not respond any event */ 
    color: #ccc; /* Gray out the text color to signify being disabled */ 
} 

現在在你的JavaScript創建這樣一個規則,只需要給元素要禁用類disabled像這樣

if (key == 1) { 
    var id = value; 
    var div = document.getElementById(id); 

    if(div != null){ 
     if (div.className.indexOf('disabled') === -1) { 
      // Your element will be visible, and disabled 
      div.className += ' disabled'; 
     } 
    } 
} 
+0

Dummy您在此指定的類名是什麼 – Murali

+0

'className'是允許您操作每個' HTMLElement' – Dummy

+0

我得到的div.className是「」(空) – Murali

0

如果您的應用程序基於在Angular上使用ng-if,這是「自然的方式」

<a ng-if="true" href="yourlink.html">Link<a/> 
<a ng-if="!true" href="#">Link<a/> 

更好嘗試覆蓋瀏覽器本地實現(鏈接...);