Html update on Jquery click event

时间:2016-06-06 14:16:32

标签: javascript jquery html html5

I have a tabbed DIV element that changes on first click but after that loses functionality

HTML:

= true

Javascript(Jquery):

<div id="holder">
<ul style="list-style:none; margin:0; padding:0;">
<li><a name="CondLink"id="onlink">Link1</a></li>
<li><a name="EffLink">Link2</a></li>
</ul>
</div>

Clicking either tab properly updates the HTML on the first click only but does does not execute either function on any followup clicks.

(NOTE: The console does not give me any errors but also does not hit a breakpoint inside either of the click functions on followup clicks)

2 个答案:

答案 0 :(得分:3)

您的进一步点击活动不起作用,因为您覆盖&#34;持有者&#34;儿童元素。 基本上,您删除它们并添加没有绑定点击事件的新元素。

简单解决方案:

替换它:

$('a[name=CondLink]').click(function(){
   // code...
});

有了这个:

$(document).on('click', 'a[name=CondLink]', function(e) {
    // code...
});

答案 1 :(得分:-1)

那是因为你正在替换你的链接。因此绑定事件侦听器不再位于新链接上,因此只需在替换链接后重新绑定它们。

function bindClicks(){
  $('a[name=CondLink]').click(function(){
    $('div[id=holder]').html('<ul style="list-style:none; margin:0; padding:0;"><li><a name="CondLink" id="onlink">Link1</a></li><li><a name="EffLink">Link2</a></li></ul>');
    bindClicks();
  });
  $('a[name=EffLink]').click(function(){
    $('div[id=holder]').html('<ul style="list-style:none; margin:0; padding:0;"><li><a name="CondLink">Link1</a></li><li><a name="EffLink" id="onlink">Link2</a></li></ul>');
    bindClicks();
  });
}
bindClicks();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="holder">
<ul style="list-style:none; margin:0; padding:0;">
<li><a name="CondLink"id="onlink">Link1</a></li>
<li><a name="EffLink">Link2</a></li>
</ul>
</div>