JQuery - One handler for multiple elements using variables

北战南征 提交于 2019-12-05 12:41:48
$([$a.get(0), $b.get(0)]).click(function(e) { ... });
$a.add($b).click(function(e){...});

add returns a new node set holding the union. $b can be "pretty much anything that $() accepts."

It seems you ca do just this:

$(deleteBtn).add(copyBtn).add(moveBtn).click(function(){});

As it says here http://api.jquery.com/add/

Depends of what you want to do next with your vars.

You could just define them as one:

var $a = $('#a, #b');
$a.click()

Or use them separately:

/* This way the click event is applied even if each selector returns
   more then one element. And $a and $b is preserved */
$([].concat($a.toArray()).concat($b.toArray())).click(function () {
    console.log(this)
});

EDIT

Updated code.

..fredrik

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!