动态添加onclick事件到锚标签,无法正常工作

时间:2022-10-22 07:58:08

i have the below anchor tag in my jsp

我在我的jsp中有以下锚标记

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

I require to stop the default, href behaviour and yet have these functions called at onclick. For the same i have written this piece of code:

我需要停止默认的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);
   });
});

However, the functions are not being called on clicking the links. Could you please tell me where I am going wrong. I am using IE 8.

但是,单击链接时不会调用这些函数。你能告诉我我哪里错了吗?我正在使用IE 8。

2 个解决方案

#1


3  

Try this:

$(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


-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)

  });
});
   

#1


3  

Try this:

$(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


-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)

  });
});