2017-09-15 102 views
-2

当用户按下链接时,我想在类jstore-js-detailLink的元素之后插入HTML。JQuery .on('click',...)不起作用

我的尝试似乎不工作:

<a href="" class="jstore-js-detailLink">hello</a> 
<div class="lsp-popup-item-name"></div> 

<script type="text/javascript"> 
jQuery(document).on('click', 'a[class^=".jstore-js-detailLink"]', function() { 
    jQuery('<div id="stars-block" class="stars">'+ 
      '<div id="reviewStars-input">'+ 
      '<input id="star-4" type="radio" name="reviewStars"/>'+ 
      '<label title="gorgeous" for="star-4"></label>'+ 
      '<input id="star-3" type="radio" name="reviewStars"/>'+ 
      '<label title="good" for="star-3"></label>'+ 
      '<input id="star-2" type="radio" name="reviewStars"/>'+ 
      '<label title="regular" for="star-2"></label>'+ 
      '<input id="star-1" type="radio" name="reviewStars"/>'+ 
      '<label title="poor" for="star-1"></label>'+ 
      '<input id="star-0" type="radio" name="reviewStars"/>'+ 
      '<label title="bad" for="star-0"></label>'+ 
      '<br>'+ 
      '</div>'+ 
      '</div>').insertAfter(".lsp-popup-item-name"); 
}); 
</script> 

回答

-1

class属性选择删除.

jQuery(document).on('click', 'a[class^="jstore-js-detailLink"]', function(){ 

} 

上面的代码被称为Attribute Starts With Selector。它为DOM中的所有anchror元素添加了一个click处理程序,该元素有一个以jstore-js-detailLink开头的类。

仅当您使用Class Selector时才添加.。在你的情况,下面的代码也将工作:

jQuery(document).on('click', 'a.jstore-js-detailLink', function() { 
    .......... 
} 

你可以把它简化为:

$("a.jstore-js-detailLink").click(function(e){ 
    e.preventDefault(); 
    ........... 
}); 

e.preventDefault()将作为一个链接,跳转到停锚页面顶部或在URL末尾添加#

+0

感谢名单 我已经使用这个: jQuery的(文件)。在( “点击”, “.jstore-JS-detailLink”,函数(){}); –

-1

将选择器更改为class^="jstore-js-detailLink"并将event.preventDefault();添加到事件处理程序中。

jQuery(document).on('click', 'a[class^="jstore-js-detailLink"]', function(event) { 
    event.preventDefault(); 
    jQuery('<div id="stars-block" class="stars">'+ 
    '<div id="reviewStars-input">'+ 
    '<input id="star-4" type="radio" name="reviewStars"/>'+ 
    '<label title="gorgeous" for="star-4"></label>'+ 
    '<input id="star-3" type="radio" name="reviewStars"/>'+ 
    '<label title="good" for="star-3"></label>'+ 
    '<input id="star-2" type="radio" name="reviewStars"/>'+ 
    '<label title="regular" for="star-2"></label>'+ 
    '<input id="star-1" type="radio" name="reviewStars"/>'+ 
    '<label title="poor" for="star-1"></label>'+ 
    '<input id="star-0" type="radio" name="reviewStars"/>'+ 
    '<label title="bad" for="star-0"></label>'+ 
    '<br>'+ 
    '</div>'+ 
    '</div>').insertAfter(".lsp-popup-item-name") 
    }); 
</script>