在jQuery中,如何通过名称属性选择元素? [英] In jQuery, how do I select an element by its name attribute?

查看:67
本文介绍了在jQuery中,如何通过名称属性选择元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网页中有3个单选按钮,如下所示:

 < label for =theme-grey> < input type =radioid =theme-greyname =themevalue =gray/> Gray< / label>< label for =theme-pink> < input type =radioid =theme-pinkname =themevalue =pink/> Pink< / label>< label for =theme-green> < input type =radioid =theme-greenname =themevalue =green/>绿色< / label>  



在jQuery中,我希望在单击这三个元素中的任何一个时获取所选单选按钮的值。在jQuery中我们有id(#)和class(。)选择器,但是如果我想通过它的名字找到一个单选按钮,如下所示?

  $(< radiobutton name属性>)。click(function(){}); 

请告诉我如何解决这个问题。

解决方案

这应该做到这一点,所有这一切都在文档,其中有一个非常类似的例子:

  $(input:radio [name = theme点击(函数(){
var value = $(this).val();
});

我还应该注意,您在该片段中有多个相同的ID。这是无效的HTML。使用类来分组元素,而不是ID,因为它们应该是唯一的。


I have 3 radio buttons in my web page, like below:

<label for="theme-grey">
  <input type="radio" id="theme-grey" name="theme" value="grey" />Grey</label>
<label for="theme-pink">
  <input type="radio" id="theme-pink" name="theme" value="pink" />Pink</label>
<label for="theme-green">
  <input type="radio" id="theme-green" name="theme" value="green" />Green</label>

In jQuery, I want to get the value of the selected radio button when any of these three are clicked. In jQuery we have id (#) and class (.) selectors, but what if I want to find a radio button by its name, as below?

$("<radiobutton name attribute>").click(function(){});

Please tell me how to solve this problem.

解决方案

This should do it, all of this is in the documentation, which has a very similar example to this:

$("input:radio[name=theme]").click(function() {
    var value = $(this).val();
});

I should also note you have multiple identical IDs in that snippet. This is invalid HTML. Use classes to group set of elements, not IDs, as they should be unique.

这篇关于在jQuery中,如何通过名称属性选择元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆