jQuery 使用jQuery,如何在名称和值已知的情况下定位元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/346542/
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 09:00:31  来源:igfitidea点击:

Using jQuery, how to locate an element when the Name and Value are known

jquerycss-selectors

提问by Jay Corbett

Thanks for reading this

感谢您阅读本文

I thought I could use find(), but couldn't make it work. I know I can add IDs or classnames, but would like to know how with the current markup.

我以为我可以使用 find(),但无法使其工作。我知道我可以添加 ID 或类名,但想知道如何使用当前标记。

Thanks

谢谢

Here is the HTML

这是 HTML

<input name="keywordCheckbox" type="checkbox" value="S" />
<input name="keywordCheckbox" type="checkbox" value="C" />
<input name="keywordCheckbox" type="checkbox" value="A" />

and the js

和 js

<script language="Javascript" src="javascript/jquery-1.2.6.min.js"></script>
<script type="text/JavaScript">

 $(function(){
  $('[name="keywordCheckbox"]').bind("click",
   function() {
    if($(this).attr("checked") == true) {
     switch(this.value) {
      case "A":
       var $_this = $(this) ;
       $('[name="keywordCheckbox"]').each(function() {
        if($(this).val() != $($_this).val()) { $(this).attr("checked",false); }
       });
       break ;
      default:
 DOESN'T WORK --> $('[name="keywordCheckbox"]').find('[value="A"]').attr("checked", false);}
      } // END Switch
    } // END If
  }); // End BIND
 }); // End eventlistener
 </script>

回答by tvanfosson

You should be able to chain the attribute selectors:

您应该能够链接属性选择器:

 $('input[name="keywordCheckbox"][value="A"]').attr("checked",false);

Will set checked to false for the input with name keywordCheckbox and value of A.

对于名称为keywordCheckbox 且值为A 的输入,将checked 设置为false。

 $('input[name="keywordCheckbox"][value!="A"]').attr("checked",false);

will set checked to false for the inputs with name keywordCheckbox whose values are not A.

对于名称为 keywordCheckbox 且值不是 A 的输入,将把检查设置为 false。

EDIT

编辑

I just tested the following in Firefox/Macintosh with the latest jQuery. Works fine. What version of jQuery are you using?

我刚刚使用最新的 jQuery 在 Firefox/Macintosh 中测试了以下内容。工作正常。您使用的是哪个版本的 jQuery?

$(document).ready( function() {
    $('input[name=keywordCheckbox]').bind( 'click', function() {
       if (this.checked) {
          if (this.value == 'A') {              
             $('input[name="keywordCheckbox"][value!="A"]')
                .attr("checked",false);
          }
          else {
             $('input[name="keywordCheckbox"][value="A"]')
                .attr("checked",false);
          }
       }
    });
});

回答by Pim Jager

Or you could do:

或者你可以这样做:

$("input[name='keywordCheckbox']").filter("input[value='A']")

Then there is no need for an each function.

那么就不需要 each 函数了。