2012-11-26 38 views
2

我有下面的錨標記在我的jsp動態添加onclick事件定位標記,不工作

<a href="javascript:submit(this)">save</a> 
<a href="javascript:alert(this)">something</a> 

我需要停止默認情況下,HREF行爲,尚未有這些功能在叫的onclick。對於同樣我寫這段代碼:

$('a[href^=\'#\']').live("click", function (e) { 
    alert("I am being called #"); 
    e.preventDefault(); 
    return false; 
}); 

$(document).ready(function(){ 
     $("a[href^='javascript']").each(function(){ 
      alert("replacing"); 
      var w=$(this).attr('href'); 

      $(this).attr('href','#'); 

      $(this).attr("onclick",w); 
    }); 
}); 

但是,功能不會被點擊鏈接調用。你能告訴我我哪裏出錯了嗎?我使用的IE 8

+0

「我要去哪裏錯了,我使用的是IE 8?」 - 那裏。 – 2012-11-26 20:39:24

+0

@ H2CO3哈哈。 - 你嘗試過'onclick = function()'嗎? –

+0

爲什麼你不在初始標記中製作href =「#」和onclick =「submit(this)」? 「onclick」不需要像/ href那樣需要「javascript:」前綴...我會是你的問題的根源。 –

回答

3

試試這個:

$(document).on("click", "a[href^=\'#\']",function (e) { 
    alert("I am being called #"); 
    e.preventDefault(); 
    return false; 
}); 

$(document).ready(function(){  
     $("a[href^='javascript']").attr('href','#');  
}); 
-2

$(document).ready(function() { 
 
    var mydiv = document.getElementById("myDiv"); 
 
    var aTag = document.createElement('a'); 
 
    aTag.setAttribute('href', "#"); 
 
    aTag.setAttribute('id', "tagId"); 
 
    aTag.innerHTML = "link text"; 
 

 
    mydiv.appendChild(aTag); 
 

 
    $("#tagId").on('click', function(e) { 
 
    alert(1) 
 

 
    }); 
 
});