Several examples of jQuery composite selector applications

  • 2020-03-30 03:55:50
  • OfStack

< ! -- the jQuery version referenced in this article's example is jQuery-1.8.3.min.js -->

The operation of the compound selector on the checkbox


<input type="checkbox" id="ckb_1" /> 
<input type="checkbox" id="ckb_2" disabled="true" /> 
<input type="checkbox" id="ckb_3" /> 
<input type="checkbox" id="ckb_4" /> 
<input type="button" id="btn" value=" Click on the ">

You need to set the type to be a checkbox and the available element to be selected

Method 1 USES the properties to filter the selector [type='checkbox'] and [disabled!=disabled]


$("input[type='checkbox'][disabled!=disabled]").attr("checked",true);

Note that in this compound selector, the "available" element should be selected with disabled! =disabled, and attr("checked",true) should be used when setting the property. The disabled property is used similarly to the checked property.

Method USES the form selector :checkbox and property filter selector [disabled!=disabled]


$('input:checkbox[disabled!=disabled]').attr("checked",true);

Method USES the form selector :checkbox and the form object property filter selector :enabled


$(':checkbox:enabled').attr("checked",true);

Method use. Each () traversal


$("input[type=checkbox]").each(function(){

if ($(this).attr("disabled") != "disabled") {

$(this).attr("checked",true);
}
});

I didn't use the compound selector. It is important to note that, as in method, you should judge whether a property is "disabled" or "enable", not false or true. Properties can be set with either "disabled" or "enable, "or false or true.

Other examples of compound selectors


<ul>
<li > The first line </li>
<li class="showli"> The second line </li>
<li class="showli"> The third line </li>
<li> In the fourth row </li>
<li style="display:none"> The fifth row </li>
<li class="showli"> The sixth line </li>
<li> Line 7 </li>
</ul>

Example. Set the background of the li element with the first class as showli to red


$("ul li[class=showli]:eq(0)").css("background":"red");

The result is' < Li class = "showli >" The second line < / li> 'the background becomes red. Attribute filter selector [class=showli] and basic filter selector eq(0) are used.

Set the background of the fifth visible li as red


$("ul li:visible:eq(4)").css({"display":"blaock","background":"red"});

The result is' < Li class = "showli >" The sixth line < / li> The background of 'display:block is to check whether the hidden li will be :visible filter, display:none can't see the red background. The visibility filter selector :visible is used

Set the background of the second li visible after the second li with the second class as showli to red


$("ul li.showli:eq(1)").nextAll("li:visible:eq(1)").css({"display":"block","background":"red"});

The result is' < Li class = "showli >" The sixth line < / li> 'the background becomes red.


Related articles: