jquery-selectors - jQuery 按名称和 ID 选择

标签 jquery-selectors

我有一张像这样的 table :

    <table>
        <tr>
            <td>
                <input type="radio" name="Sample1" id="Sample1" value="1" />
                <input type="radio" name="Sample1" id="Sample2" value="1" />
            </td>
            <td>
                <input type="radio" name="Sample2" id="Sample1" value="1" />
                <input type="radio" name="Sample2" id="Sample2" value="1" />
            </td>
            etc....
        </tr>
    </table>

我希望能够通过 name 选择特定的单选按钮和 id .例如,选择名称为 Sample2 的单选按钮和 ID Sample1 .我尝试这样做:
    $('[id="Sample1"][name="Sample2"]').checked = true;

但没有运气......我应该怎么做?

最佳答案

 $('#Sample1[name="Sample2"]').attr('checked','checked');

但是元素只能有一个 id 所以也许你想要 class 而不是 id
  $('.Sample1[name="Sample2"]').attr('checked','checked');

然后你的html
<table>
    <tr>
        <td>
            <input type="radio" name="Sample1" class="Sample" value="1" />
            <input type="radio" name="Sample1" class="Sample" value="1" />
        </td>
        <td>
            <input type="radio" name="Sample2" class="Sample1" value="1" />
            <input type="radio" name="Sample2" class="Sample2" value="1" />
        </td>
    </tr>
</table>

编辑

在这里做了一些更改 working demo

关于jquery-selectors - jQuery 按名称和 ID 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5636513/

相关文章:

jQuery 选择器不是这个子元素

javascript - 替代 .selector 属性,现在它已在 jQuery 1.9 中删除

javascript - 在 jQuery 中选择多个元素不起作用

javascript - 为什么最后一个元素总是在悬停时触发?

jquery - 如何在 jQuery 中定位较早的非同级元素?

javascript - 在 jquery 中转义选择选项值

jquery - jquery 选择器帮助

javascript - jQuery :empty not working with input

javascript - 使用数组检查一系列 javascript 按钮

jquery - 如何将ajax html响应附加到当前div的旁边