手动触发div的点击事件 [英] trigger click event of div manually
问题描述
我有一个div,它有很多divs.when绑定divs我为每个项目创建点击事件,如下所示
i have a div which has many divs.when binding the divs i create click event for each item like below
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
}
当UI在UI中点击被触发时,我尝试手动执行它不被触发任何帮助如何触发将是伟大的
i硬编码的div值,并试图调用,但它是没有用的。
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.
var id1 = 'Car';
var id2 = 'Bus';
$('div class="CList" id="1" >' + id1 + '</div>').trigger('click');
$('div class="CList" id="3" >' + id2 + '</div>').trigger('click');
即使这样
var id1 = 'Car';
var id2 = 'Bus';
$('div class="CList" id="1" >' + id1 + '</div>')[0].click();
$('div class="CList" id="3" >' + id2 + '</div>')[0].click();
推荐答案
你所拥有的是无效的选择器。你传递的东西几乎是HTML到jQuery函数,所以它不知道该怎么做。
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.
如果元素的ID是 1
和 3
,那么你只要这样做:
If the IDs for your elements are 1
and 3
, then you'd just do:
$('#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');
});
这篇关于手动触发div的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!