jQuery 手动触发div的点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19786107/
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:35:50  来源:igfitidea点击:

trigger click event of div manually

jqueryevents

提问by G--

i have a div which has many divs.when binding the divs i create click event for each item like below

我有一个 div,它有很多 div。绑定 div 时,我为每个项目创建单击事件,如下所示

    jQuery.each(opts.items, function (i, item)
                    {
                        var image = opts.image;
                        jQuery('jQuery('<div class="' + opts.optionClassName + opts.controlId + '" id="' + item.key + '" ><img src="' + image + '" alt="checkbox" />' + item.value + '</div>')
                                .click(function ()
                                {')
                                        .click(function ()
                                        {

    //code goes here

    }

when the div is clicked in UI this gets triggered, but when i try to do it manually it does not get triggered. any help on how to trigger would be great. i hardcoded the div values and tried to call but it is of no use.

当在 UI 中单击 div 时,这会被触发,但是当我尝试手动执行时,它不会被触发。关于如何触发的任何帮助都会很棒。我对 div 值进行了硬编码并尝试调用,但它没有用。

   var id1 = 'Car';
    var id2 = 'Bus';
    $('div class="CList" id="1" >' + id1 + '</div>').trigger('click');
    $('div class="CList" id="3" >' + id2 + '</div>').trigger('click');

even this

甚至这个

    var id1 = 'Car';
    var id2 = 'Bus';
    $('div class="CList" id="1" >' + id1 + '</div>')[0].click();
    $('div class="CList" id="3" >' + id2 + '</div>')[0].click();

回答by Anthony Grist

What you have aren't valid selectors. You're passing something that's almost HTML to the jQuery function so it doesn't know what to do with it.

您拥有的不是有效的选择器。您将一些几乎是 HTML 的东西传递给 jQuery 函数,因此它不知道如何处理它。

If the IDs for your elements are 1and 3, then you'd just do:

如果您的元素的 ID 是1and 3,那么您只需执行以下操作:

$('#1, #3').trigger('click');

Perhaps a better way, if you want to simulate the click on each of them, is to iterate over your collection again:

也许更好的方法是,如果您想模拟对它们中的每一个的点击,则再次迭代您的集合:

jQuery.each(opts.items, function(i, item) {
    $('#' + item.key).trigger('click');
});

回答by Igle

Get you Elements via Jquery and use trigger function ;)

通过 Jquery 获取元素并使用触发器功能;)

$("#yourdesiredselementsid").trigger("click");

回答by Abide Masaraure

Give your outer div a class name

给你的外部 div 一个类名

  <div class="display">
   <div id="1"></div>
   <div id="2"></div>
    </div>

And then

进而

$('.display').on('click','div',function (e) {

alert('hey');
  });