简体   繁体   English

为什么事件无法在jquery中触发?

[英]why event not fire in jquery?

could you please tell me why click event is not firing when I am taking selector in object ; 您能告诉我为什么在object selector时click事件没有触发吗? here is my code https://jsbin.com/seregezahe/1/edit?html,js,output 这是我的代码https://jsbin.com/seregezahe/1/edit?html,js,输出

(function(){
  $(function(){
    var config ={
      btn:$('#btn'),
      hello:$('.hello'),
       bodyClickEvent: $("body"),
       overlayClick: $('.overlay'),
      closeBtnSelector: '#closeBtn',
    };
  config.btn.click(function(){
    $('#container').append($('#overlay').html())
    $('.popupdata').html('<div class="hello">xxxx</div><a href="javascript:void(0)"  id="closeBtn" >X Close</a></div>');


  })
  config.bodyClickEvent.on("click", config.closeBtnSelector, function () {

    //why it is not working
    config.overlayClick.fadeOut(500);
               config.overlayClick.remove();
    // below code is working fine
               //$('.overlay').fadeOut(500);
               //$('.overlay').remove();
            });

})
})()

why these two line are not working 为什么这两条线不起作用

 config.overlayClick.fadeOut(500);
               config.overlayClick.remove();

when I run my code it show a button when I click on button some html is show with close button text .When I click close button it is not fadeout my html and remove. 当我运行我的代码时,当我单击button时,它会显示一个buttonsome html is show带有关闭按钮文本。当我单击关闭按钮时,它不会fadeout我的html并删除。

Update the config object after updating the dom 更新dom后更新配置对象

config.btn.click(function(){
    $('#container').append($('#overlay').html())
    $('.popupdata').html('<div class="hello">xxxx</div>'+
                         '<a href=""  id="closeBtn" >X Close</a></div>');
    config.overlayClick= $('.overlay');
    config.closeBtnSelector = '#closeBtn'
    return false;
  })

The problem is your are selecting the elements before they are added to the page. 问题是您在将元素添加到页面之前正在选择它们。 You need to populate the selectors after you add them to the page. 将选择器添加到页面后,需要填充它们。

....append(...);
....html(...);
config.overlayClick = $('.overlay'); 
...

or you need to select the items instead of using the variable. 或者您需要选择项目而不是使用变量。

var config ={
  btn:$('#btn'),
  hello:$('.hello'),
  bodyClickEvent: $("body"),
  overlayClick: $('#overlay'),
  closeBtnSelector: '#closeBtn',
};

Because the element #overlay is not exist when you call $('#overlay') above, so the $('#overlay') return an empty list. 因为当您调用上面的$('#overlay')时元素#overlay不存在,所以$('#overlay')返回一个空列表。

The following code should work: 下面的代码应该工作:

var config ={
  btn:$('#btn'),
  hello:$('.hello'),
  bodyClickEvent: $("body"),
  overlayClickSelector: '#overlay',
  closeBtnSelector: '#closeBtn',
};

config.bodyClickEvent.on("click", config.closeBtnSelector, function () {         
  $(config.overlayClick).remove();
});

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

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