分享一段通過前端javascript指令碼 啟用/禁用超連結的代碼

來源:互聯網
上載者:User

在做asp.net開發的時候,可能會經常用LinkButton,該控制項最終會在用戶端解析成超連結;

有的時候可能期望直接在用戶端控制 該類button(即hyperlink)的可用與非可用。

一般我們會在用戶端這樣寫:

<a href="javascript: doSomething()" class="button" id="abc">審核</a>或者<a href="#" onclick="doSomething(); return false;" class="button" id="xyz">審核</a>

在ie裡面可以直接設定超連結的disabled屬性為true,但是有兩個問題:

1)disabled屬性只有ie支援,其它瀏覽器(如firefox、Opera等)未必支援;

2)即使將disabled屬性設定為true以後,在單擊該超連結的似乎後,onclick事件仍然會執行;

因此出現了下面變通的方法,經實驗,瀏覽器安全色性比較好,提供點小技巧供參考:

// 禁用、啟用超連結
// @objId : 超連結ID
// @disable: true,禁用; false:啟用
function disableAnchor(objId, disable) {
var obj = gId(objId);
if (disable) { // disable
var href = obj.getAttribute("href");
if (href && href != "" && href != null) {
obj.setAttribute('href_bak', href);
}
obj.removeAttribute('href');
// 處理onclick事件
var onclick = obj.getAttribute("onclick");
if(onclick != null){
obj.setAttribute('onclick_bak', onclick);
obj.setAttribute('onclick', "void(0);");
}
obj.onclick = null;
obj.style.color = "gray";
obj.setAttribute('disabled', 'disabled');
}
else { // enable
if (obj.attributes['href_bak'])
obj.setAttribute('href', obj.attributes['href_bak'].nodeValue);
if(obj.attributes['onclick_bak']!=null)
obj.setAttribute('onclick', obj.attributes['onclick_bak'].nodeValue);
obj.removeAttribute('style');
obj.removeAttribute('disabled');
}
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.