开发者

Refactor jquery to pass jquery-lint

开发者 https://www.devze.com 2023-01-23 19:34 出处:网络
I have the following code in an html page jQuery(\"input[name=\'newstate\']\").change(function(){ if(jQuery(this).attr(\"checked\")) {

I have the following code in an html page

jQuery("input[name='newstate']").change(function(){
    if(jQuery(this).attr("checked")) {
        jQuery('input[name="new-state-开发者_如何转开发name"]').show();
    } else {
        jQuery('input[name="new-state-name"]').hide();
    }
});

But jquery lint gives following message.

You should only use the same selector more than once when you know the returned collection will be different. For example, if you've added more elements to the page that may comply with the selector

How do I modify my code to remove this message


The .toggle() method accepts a Boolean for showOrHide:

jQuery("input[name='newstate']").change(function(){
    // You can use this.checked instead of jQuery(this).attr("checked");
    jQuery('input[name="new-state-name"]').toggle(this.checked);
});

This way you'll know that the new-state-name input's display state always matches the newstate input (i.e., it will show when checked, unregarding it's previous state). What I mean is, using toggle() without showOrHide you can risk that the newstate state and new-state-name display state runs out of sync if e.g. the new-state-name input's display state is manipulated from outside the newstate change() handler.


Of course you could also just assign the result set to a temporary variable in order to perform the selector only once:

jQuery("input[name='newstate']").change(function(){
    var newStateInput = jQuery('input[name="new-state-name"]');
    if(this.checked) {
        newStateInput.show();
        // ... more here
    } else {
        newStateInput.hide();
        // ... and/or here
    }
});

if you intend to do more than show/hide.


EDIT
Oops, unfortunate typo. show() should be toggle() in first solution.


jQuery("input[name='newstate']").change(function(){
      jQuery('input[name="new-state-name"]').toggle();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消