On('click')无效,但click()正常

时间:2019-12-09 03:16:28

标签: javascript jquery

我有一个奇怪的问题。我有一个附加的项目,其中包含一个图钉标签,我想在单击该按钮时添加一个类。但是on()无效

HTML

<div id="lookbook-image260">
  <img src="abc" alt="//image here">
  <div class="button-style has-label position-top" id="slider-popup204" style="top: 0%; left:0%; background-color : #BBFAFF; color: #F0FF94; width : 40px; height: 40px">
// the label in pin label for when you hover it appears
    <div class="pin-label" data-lookbook-container="slider-popup204" style="line-height:40px">
      <span>+</span>
      <span class="label">jo</span>
    </div>
//content of popup
    <div class="popup pin-popup position-top" id="slider-custombutton204" value="0">
      <div>
        <div class="popup-title">jo</div>
        <div class="popup-custom-text">uy</div>
        <span class="slider-addtocart" id="291885956"><a href="cart">Add to cart</a></span>
      </div>
    </div>
  </div>
</div>

JS

//the .pin-label don't have the event
$(document).on('click',".pin-label", function () {
    console.log('1');//this wont show in console
    $(this).parent().toggleClass('active');
});

//but this one work
$(".pin-label").click(function () {
console.log('2');// this show in console
    $(this).parent().toggleClass('active');
});

// The other on() fails but this on() works. .slider-addtocart is also an appended div.
$(document).on('click', ".slider-addtocart", function(e) {
    e.preventDefault();
}

我正在使用Jquery 2.2.3。当检查元素时,在附加元素后只有针形标签。我还清除了缓存并将这两个js包装在$(document).ready(function() {}中。谁能帮我吗?

1 个答案:

答案 0 :(得分:-1)

好像您的HTML中没有类 .pin-label 的元素

$(document).on('click',".pin-label", function ()

尝试更改与之相关的类元素。是否可以共享与此相关的其他代码。