要正式回答你的问题:用一条线:
//If this is only one use variable you can use
$(['#p1','#p2','#p3','#p4','#p5'].join(',')).methodToUse();
//if you DO need it as a variable you can
var joined = ['#p1','#p2','#p3','#p4','#p5'].join(',');
$(joined).methodsToUse();
如果你想让他们单独做某事,还有 .each();
在下面的示例中,每个 p id 点击都会使其中任何一个变为红色:
var peas = ['#p1','#p2','#p3','#p4','#p5'];
$.each(peas, i => {
$(peas[i]).click(() => {
$(peas[i]).css({'color':'red'});
});
});
当您将“i”放入函数参数时,它会适当地找到数组中的值。当您执行 '.each()' 时,格式如下所示:
$.each(array, function(i){
// any code you wish as long as you have an array selector
//$(array[i]).whatever function
});
一个更大的例子。假设你想让你点击的 P 变成红色,但想让其他 ps 恢复默认颜色。只需创建一个从数组中删除所选 ID 的函数,瞧!
var peas = ['#p1','#p2','#p3','#p4','#p5'],
poppy=(v,i)=>peas.toString().replace(`,${v[i]}`,'').replace(`${v[i]},`,'');
(// get each pea index
$.each(peas,i=>///funciton(i){ code inside}
(//set up each individual index's functions
$('.peastock').append(`<p id="p${[i+1]}">I am ${peas[i]}</p>`),
$(peas[i]).click(()=>(
$(peas[i]).css({"color":"red","background-color":"rgba(128,0,0,0.1)"}),
$(poppy(peas,i)).css({'color':'black','background-color':'rgba(255,255,255,0.2)'}))))),
$('.peastock').append(`
<div id="ree">ES6 isnt suitable for all of jQuery's usage!</div>
<div>Since some functions inside of jQuery's methods dont require 'this' or 'return'</div>
<div>You can learn this by going <a href="https://www.w3schools.com/Js/js_es6.asp">here</a></div>
`),
$("*").css({"margin":"0 auto","padding":"1%"}),
$("* .peastock, .peastock, .peastock *").css({"background-color":"rgba(128,0,0,0.1)"})
);
我知道有人一定想知道每个值数组作为 jquery 选择器。希望一切顺利!
来源:
jQuery .each()
The fiddle in action (with updates!)