gpt4 book ai didi

javascript - 一次将事件附加到多个元素

转载 作者:IT王子 更新时间:2023-10-29 02:58:40 26 4
gpt4 key购买 nike

假设我有以下内容:

var a = $("#a");
var b = $("#b");

//I want to do something as such as the following :

$(a,b).click(function () {/* */}); // <= does not work

//instead of attaching the handler to each one separately

显然上面的代码不起作用,因为在 $ 函数中,第二个参数是 context ,而不是另一个元素。

那么我怎样才能一次性将事件附加到两个元素呢?


[更新]

peirix发布了一个有趣的片段,其中他将元素与 & 符号结合在一起;但是我注意到了这一点:

$(a & b).click(function () { /* */ }); // <= works (event is attached to both)

$(a & b).attr("disabled", true); // <= doesn't work (nothing happens)

从上面可以看出,显然,与 & 符号的组合仅在附加事件时才有效...?

最佳答案

jQuery add method是你想要的:

Adds more elements, matched by the given expression, to the set of matched elements

var a = $("#a");
var b = $("#b");
var combined = a.add(b)

关于javascript - 一次将事件附加到多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1388018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com