点击()不会从<a href=""> when link is clicked

时间:2017-10-24 01:58:03

标签: jquery click

Just wondering what the issue is with click() firing from an a href.

Code snippet below, thanks ahead of time guys.

$(document).ready(function(){
   // (4n+4) selects every 4th p starting at 4 onward
   $('<a href="#top" class="bac">back to top</a>').insertAfter('div.chapter p:nth-child(4n+4)');
   $('a id="top">,/a>').prependTo('body');

   $('.bac').click(function() {
       alert("Testing");
   });
});

3 个答案:

答案 0 :(得分:1)

以下行中的字符串'a id="top">,/a>'会导致错误,因为jQuery不知道如何处理它(它不是有效的HTML而不是有效的选择器):< / p>

$('a id="top">,/a>').prependTo('body');

那么之后不会达到.click()绑定的代码。

修复该字符串中的HTML以创建锚点:

$('<a id="top"></a>').prependTo('body');

答案 1 :(得分:0)

您可能需要使用preventDefault   - https://api.jquery.com/event.preventdefault/

$(".bac").click(function( event ) {
  event.preventDefault();
  alert("Testing");
});

答案 2 :(得分:0)

认为这样可行

$( '#' 顶部)prependTo( '主体');

相关问题