简体   繁体   English

在jQuery中单击时按钮不起作用

[英]The button does nothing on click in jquery

I am learning jquery and i am stuck with a problem. 我正在学习jQuery,但遇到了问题。

Here is the code 这是代码

$(function(){
  var gotProducts=new Array();
  var productsWithDelete=new Array();
  $('.addProducts').on('keyup',function(event) {
    var searchVal=$(this).val().trim();
    if(searchVal.length > 0) {
      $.ajax({
        url: 'http://localhost/url',
        data: { products: $(this).val(), },
        type: 'POST',
        dataType: 'html',
        success: function(msg) {
          $('#printTheProducts').html(msg);
        }
      });
    }
  });

  $('.productsButton').click(function() {
    alert('yes');
  });

});

The response I am getting from the ajax call is a button having class productsButton . 我从ajax调用中得到的响应是一个具有class productsButton类按钮

Now when i try to click that button I got through ajax then it does not alert yes . 现在,当我尝试单击该按钮时,我通过了ajax,但它不会警告yes I mean it does nothing. 我的意思是什么也没做。

Question:- 题:-

What might be the problem? 可能是什么问题?

Try event delegation using .on() for generated button, As they are generated dynamically 尝试使用.on()对生成的按钮进行事件委托,因为它们是动态生成的

$('#printTheProducts').on('click','.productsButton',function(){
    alert('yes');
});

Where #printTheProducts is the closest parent element, you can use document or document.body also as a selector! 如果#printTheProducts是最接近的父元素,则可以将documentdocument.body用作选择器!

Syntax: 句法:

$(closestparentelement).on('event','targetselector',function(){
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM