1. 程式人生 > >js 重寫a標簽的href屬性和onclick事件

js 重寫a標簽的href屬性和onclick事件

document 點擊 但是 () move ttr 單擊事件 can remove

適應場景:假如移動端撥打電話,需要給a標簽添加href屬性,但是由於需求,需要鏈接跳轉的同時給a標簽添加onclick事件,如果不做任何處理的話,默認執行點擊事件,而不會跳轉href屬性的鏈接。

怎麽解決:重寫a標簽的href屬性和onclick事件

//這段代碼可放入點擊事件裏

(function(){

this.fnCancel(); var _event_list = {}; // 找到頁面上所有的a標簽 var links = document.getElementsByTagName("a")[0]; // 保存click屬性的值 var _click = links.getAttribute("onclick"); // 保存href屬性的值 var _href = links.getAttribute("href"); if (_click != null) { // 給onclick屬性重新設值 links.setAttribute("onclick", "eval_a_click_event(‘a‘)"); } if (_href != null) { // 給href屬性重新設值 links.setAttribute("href", "javascript:eval_a_href_event(‘a‘)"); } _event_list["a"] = [links, _href, _click];

})()

function eval_a_href_event(id) { var link = _event_list[id]; if (link != null && link[1] != null) { // 拿到href屬性的值 alert(link[1]); // 將href屬性值重新賦回原來的值 link[0].setAttribute("href", link[1]); // 移除單擊事件 link[0].removeAttribute("onclick"); // 模擬單擊事件 link[0][0].click(); // 重寫href屬性的值 link[0].setAttribute("href", "javascript:eval_a_href_event(‘" + id + "‘)"); // 如果有單擊事件,重新加上 if (link[2] != null) { link[0].setAttribute("onclick", link[2]); } } } function eval_a_click_event(id) { var link = _event_list[id]; if (link != null && link[2] != null) { // 拿到單擊事件的方法 alert(link[2]); // 執行單擊事件 eval(link[2]); } }

js 重寫a標簽的href屬性和onclick事件