[英]How to Simplify Javascript Dynamic IDs?
我是JS的新手,正在运行CMS,我有一个动态ID,我担心的是,我将通过添加ID数组来简化ID以减少JS代码。
你们能帮我简化代码吗
$x1(document).ready(function () {
//
// Id1 = #options_1_text
// Id2 = #option_2_text
// Id3 = #option_3_text
// Id(n) = so on..
$x1("#options_1_text").miniColors({
letterCase: 'uppercase',
change: function (hex, rgb) {
logData('change', hex, rgb);
}
});
$x1("#options_2_text").miniColors({
letterCase: 'uppercase',
change: function (hex, rgb) {
logData('change', hex, rgb);
}
});
$x1("#options_3_text").miniColors({
letterCase: 'uppercase',
change: function (hex, rgb) {
logData('change', hex, rgb);
}
});
// so on..
});
非常感谢您的帮助!
谢谢!
尝试这个:
$x1(document).ready(function () {
var ids = [
"#options_1_text",
"#options_2_text",
"#options_3_text",
"#options_4_text",
.
.
.
.
."#options_n_text",
];
$x1.each(ids, function(i, el){
$x1(el).miniColors({
letterCase: 'uppercase',
change: function (hex, rgb) {
logData('change', hex, rgb);
}
});
});
});
如果代码对所有元素所做的确实相同:
for (var i=1; i<4; i++) {
$x1("#options_"+i+"_text").miniColors({
letterCase: 'uppercase',
change: function(hex, rgb) {
logData('change', hex, rgb);
}
});
}
如果id不是像这样的简单序列
var ids = [ 'id1', 'another_id', 'one_more' ];
然后遍历该数组 。
var str='',n=4;
for (var i=1; i<n; i++) {
str+=",#options_"+i+"_text";
}
str[0]='';
$x1(str).miniColors({
letterCase: 'uppercase',
change: function (hex, rgb) {
logData('change', hex, rgb);
}
});
这里最简单的方法是为每个项目添加一个通用类,并让jQuery为您完成所有工作,因此您可以这样做:
$x1(document).ready(function () {
$x1(".options_text").miniColors({
letterCase: 'uppercase',
change: function (hex, rgb) {
logData('change', hex, rgb);
}
});
});
如果您无法修改HTML,并且可以假定项目从1开始按顺序编号,则可以动态查找现有元素:
$x1(document).ready(function () {
var i = 1, elem;
while (elem = document.getElementById("options_" + i + "_text")) {
$x1(elem).miniColors({
letterCase: 'uppercase',
change: function (hex, rgb) {
logData('change', hex, rgb);
}
});
i++;
}
});
如果这是一个简单的模式,并且您不知道元素的数量n,则可以这样操作:
var n = 1;
while($('#options_'+n+'_text').length > 0)
{
$x1('#options_'+n+'_text').miniColors({
letterCase: 'uppercase',
change: function (hex, rgb) {
logData('change', hex, rgb);
}
});
n++;
}
好吧,这里有一个结构:
$x1(document)
.ready(function () {
$x1("#options_1_text")
.miniColors({
letterCase: "uppercase",
change: function (a, b) {
logData("change", a, b)
}
}), $x1("#options_2_text")
.miniColors({
letterCase: "uppercase",
change: function (a, b) {
logData("change", a, b)
}
}), $x1("#options_3_text")
.miniColors({
letterCase: "uppercase",
change: function (a, b) {
logData("change", a, b)
}
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.