单击 jQuery 中 div 上的事件失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7645680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:06:59  来源:igfitidea点击:

Click event failing on div in jQuery

jqueryjquery-events

提问by Ashutosh Mishra

I am using the below code:

我正在使用以下代码:

<div class="business-bottom-content" onMouseOver="javascript:this.className='business-bottom-    content-hover';"  onMouseOut="javascript:this.className='business-bottom-content';"> 

The jQuery script is as following:

jQuery 脚本如下:

 $("div.business-bottom-content").click(
 function()
  {
   alert('ashutosh mishra');
  });

回答by ThiefMaster

You probably define the div after the script has executed.

您可能在脚本执行后定义了 div。

Wrap it in $(document).ready(function() { .... });to ensure it executes after the full DOM is available.

将其包裹起来$(document).ready(function() { .... });以确保它在完整 DOM 可用后执行。

Additionally you should get rid of those ugly inline events (if you even need them - you can use :hoverin CSS):

此外,您应该摆脱那些丑陋的内联事件(如果您甚至需要它们 - 您可以:hover在 CSS 中使用):

$('div.business-bottom-content').hover(function() {
    $(this).addClass('business-bottom-content-hover');
}, function() {
    $(this).removeClass('business-bottom-content-hover');
});

回答by Madhu

You can try this for div class have to mention "."

你可以试试这个 div 类不得不提“。”

 $(".business-bottom-content").click(
 function()
 {
      alert('ashutosh mishra');
 });

回答by Ron16

In some scenarios even wrapping it in a $(document).ready(function() { .... });may not be enough. In that case, just use a timeout function.

在某些情况下,即使将其包装在 a 中$(document).ready(function() { .... });也可能不够。在这种情况下,只需使用超时功能。

HTML

HTML

<div id="up-button" class="inc button-number-cart">
 <span class="up-arrow">+</span>
</div> 

JS

JS

setTimeout(function(){
        $(document).on('click','.button-number-cart',function(){
            event.preventDefault();


            const button = $(this);
            const oldValue = button.parent().parent().find('input').val();
            let newVal;

            if (button.find('.up-arrow').length !== 0) {
                newVal = parseFloat(oldValue) + 1;
            } else {
                if (oldValue > 0) {
                    newVal = parseFloat(oldValue) - 1;
                } else {
                    newVal = 0;
                }
            }
            button.parent().parent().find('input').val(newVal);
        });
 },700);