jQuery 匹配多个属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/155977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:43:14  来源:igfitidea点击:

jQuery match multiple attributes

jqueryhtmljquery-selectors

提问by zadam

I have the following markup, and I want to make the Allradio button checked.

我有以下标记,我想让All单选按钮被选中。

<ul>
    <li><input type="radio" value="All" name="Foo"/>All</li>
    <li><input type="radio" value="New" name="Foo"/>New</li>
    <li><input type="radio" value="Removed" name="Foo"/>Removed</li>
    <li><input type="radio" value="Updated" name="Foo"/>Updated</li>
</ul>

I'd like to match via attribute, but I need to match on 2 attributes, @name='Foo'and @value='All'.

我想通过属性匹配,但我需要匹配 2 个属性,@name='Foo'并且@value='All'.

Something like this:

像这样的东西:

$("input[@name='Foo' @value='all']").attr('checked','checked');

Can someone show how this can be done?

有人可以展示如何做到这一点吗?

回答by paxdiablo

The following HTML file shows how you can do this:

以下 HTML 文件显示了如何执行此操作:

<html>
  <head>
    <script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        $("a").click(function(event){
          $("input[name='Foo'][value='All']").attr('checked','checked');
          event.preventDefault();
        });
      });
    </script>
  </head>
  <body>
    <ul>
      <li><input type="radio"  value="All"  name="Foo"  />All</li>
      <li><input type="radio"  value="New"  name="Foo"  />New</li>
      <li><input type="radio"  value="Removed"  name="Foo"  />Removed</li>
      <li><input type="radio"  value="Updated"  name="Foo"  />Updated</li>
    </ul>
    <a href="" >Click here</a>
  </body>
</html>

When you click on the link, the desired radio button is selected. The important line is the one setting the checkedattribute.

单击链接时,会选择所需的单选按钮。重要的一行是设置checked属性的那一行。

回答by easel

I was beating my head against a wall similar to this and just want to point out that in jQuery 1.3 the syntax used in the accepted answer is the ONLY syntax that will work. The questioner uses the @ syntax for the expression which does not work at all in jQuery. Hopefully this helps the next guy to come across this question via Google =p

我在与此类似的墙上撞墙,只想指出,在 jQuery 1.3 中,接受的答案中使用的语法是唯一可行的语法。提问者对表达式使用 @ 语法,这在 jQuery 中根本不起作用。希望这有助于下一个通过 Google =p 遇到这个问题的人

To be clear, you have to use

要清楚,你必须使用

jQuery('input[name=field1][val=checked]') 

and not

并不是

jQuery('input[@name=field1][@val=checked]')