2015-12-01 133 views
2

首先,对于标题感到抱歉,我知道这不是很具体,但我真的很难说还有什么要说的。如何使用jQuery选择具有相似属性的元素?

所以之前我尝试在我的问题是什么罗嗦了,你不妨看看这个的jsfiddle我做: http://jsfiddle.net/ax1ncdmu/2

它是如何工作在这个小提琴正是我希望的方式工作,但正如你所看到的,jQuery是这样的:

$(document).ready(function() { 
    $("input[name=guest0]").click(function() { 
    $('#guest0').toggle(); 
    }); 
    $("input[name=guest1]").click(function() { 
    $('#guest1').toggle(); 
    }); 
    $("input[name=guest2]").click(function() { 
    $('#guest2').toggle(); 
    }); 
}); 

但似乎很草率写出这样的代码,只是在重复同样的事情一遍又一遍。我觉得这应该是显而易见的,但之前我没有使用jQuery,所以我很难找出它。

有没有办法找出被点击的复选框的“名称”,然后使用该字符串插入代码?或者这是错误的方式呢?

回答

8

您可以使用jQueries attribute-starts-with-selector

$(document).ready(function() { 
    // all inputs that its name starts with "guest" 
    $("input[name^=guest]").click(function() { 
    // read the name and apply to id 
    $('#'+$(this).attr('name')).toggle(); 
    }); 
}); 

看到它的工作:

http://jsfiddle.net/ax1ncdmu/7/

+3

'$(本).attr( '名')'可以用'this.name取代' –

+0

是的,但我经常使用jQuery,因为它使兼容性变得简单。在这种情况下,没有问题,但在浏览器在属性中运行不同的情况下,jQuery避免为不同的浏览器编写不同的代码,并且它不会打扰;) –

+1

非常感谢您在评论中添加注释以及:) – chilliconcode

相关问题