我可以自动生成一个jquery块,对不同的元素做同样的事情吗

Can I automatically generate a jquery block that does the same thing to different elements?

本文关键字:元素 自动生成 jquery 一个 我可以      更新时间:2024-04-11

为了简单起见,假设我有一个元素列表"#a1,a2,a3,a4…"和另一个列表"#b1,b2,b3,b4…"。我希望单击#a1时显示#b1,单击#a2时显示#b2,依此类推。

我可以写:

$("#a1").click(function() {
  $("b1).show();
});
$("#a2").click(function() {
  $("b2).show();
});
...

等等。但如果列表变长,那将是大量的代码。

有没有办法自动生成jQuery?这里有一些非常粗糙的rails-y伪代码来说明我想做什么:

for (ids a1 - a99).each do |id|
  $("#a[id]").click(function() {
    $("#b[id]).show();
  });
end

不添加id,而是添加一个类。并使用以下方案

$( ".classA" ).click( function() {
    // get index of clicked element among elements with classA
    var index = $( ".classA" ).index( this );  
    // show element from classB with same index as clicked element
    $( ".classB" ).eq( index ).show();  
} );

一把简单的小提琴https://jsfiddle.net/xjseca5d/

使用substr()剪切整数部分(或使用只返回包含的整数值的parseInt()),然后使用:$(".myControls").on("click", function(){ $("#b"+ //the id in question).show(); }); .myControls是所有需要与该函数连接的元素的选择器。

使用一个以选择器开头的选择器,并使用regex获取数字。

$('[id^="a"]').click(function(){
   var number = /'d+/.exec(this.id)[0];
   $('#b' + number).show()
});

我认为循环可能就足够了。附加document ready中的所有处理程序。

// arr is an array of int, according to your DOM
$.each(arr, function(){
  $("#a"+this).click(function() {
    $("#b"+this).show();
  });
});

你可以试试这个

$('div[id^="a"]').on("click",function(){
    this.id.replace('a', 'b')).show();
})

将类"a"添加到所有"a"元素,将类"b"添加到所有"b"元素,

在类"a"上附加一个click事件,将ID中的字母"a"替换为"b"。

$('.a').click(function(){
   $('#'+this.id.replace('a','b')).show();
});

对于高级案例,我推荐这个很棒的插件:http://james.padolsey.com/javascript/regex-selector-for-jquery/

您将能够使用如下regex模式选择元素:

jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
                matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels, '')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^s+|s+$/g, ''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}
alert($(":regex(id,a[0-9]{2})").length);
$(":regex(id,a[0-9]{2})").click(function() {
    var numberPart = /'d+/.exec(this.id)[0];
    alert($("#b" + numberPart).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a9">a9</div>
<div id="b99">b99</div>
<div id="a99">a99</div>