简体   繁体   English

通过名称jQuery的一部分选择元素

[英]Select Element by part of the name jQuery

I need to check if the checkbox is checked, the thing is the check box has name and id and I can't use them as it is a sharepoint site and both name and id could be changed once a new element introduced to the page. 我需要检查复选框是否被选中,问题是该复选框具有名称和ID,我不能使用它们,因为它是一个共享站点,一旦在页面上引入了新元素,名称和ID都可以更改。 What should I do? 我该怎么办?

<tr>
    <td nowrap="true" valign="top" width="190px" class="ms-formlabel"><h3 class="ms-standardheader">
    <nobr>All employees in department</nobr>
</h3></td>
    <td valign="top" class="ms-formbody">
    <!-- FieldName="All employees"
         FieldInternalName="All_x0020_employees_x0020_in_x00"
         FieldType="SPFieldBoolean"
      --> 
 <span dir="none">
    <input id="ctl00_m_g_49618ec6_4999_44aa_87e7_6087a1cf4a6f_ctl00_ctl05_ctl00_ctl00_ctl00_ctl04_ctl00_ctl00_BooleanField" 
    type="checkbox" name="ctl00$m$g_49618ec6_4999_44aa_87e7_6087a1cf4a6f$ctl00$ctl05$ctl00$ctl00$ctl00$ctl04$ctl00$ctl00$BooleanField" /><br />
</span>
        select employees !

    </td>

You can use javascript's querySelector() and a CSS selector, like this 您可以使用javascript的querySelector()和CSS选择器,如下所示

if (document.querySelector('input').checked) {
  // checked, so do something
}

And if you only want the input in the td with class ms-formbody , like this 而且,如果您只希望使用类ms-formbodytd input ,就像这样

if (document.querySelector('td.ms-formbody input').checked) {
  // checked, so do something
}

Additionally, if you know eg the beginning of the name will always be the same, you can use the start with attribute selector [attribute^="value"] 此外,如果您知道例如name的开头将始终相同,则可以使用“ 开始于”属性选择器[attribute^="value"]

if (document.querySelector('input[name^="ct100"]').checked) {
  // checked, so do something
}

or if the end of the name will, use the end with attribute selector [attribute$="value"] 或者,如果name的结尾将使用带有属性选择器的结尾 [attribute$="value"]

if (document.querySelector('input[name$="BooleanField"]').checked) {
  // checked, so do something
}

For jQuery, use its .prop() method combined with any of the above selectors 对于jQuery,将其.prop()方法与上述任何选择器结合使用

if ($( "selector" ).prop("checked")) {
  // checked, so do something
}

当属性从某个字符串开始时,使用jQuery选择器

$( "input[name^='ctl00']" ).is( ":checked" )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM