Difference between :checked and :selected when working with option elements in jQuery

六月ゝ 毕业季﹏ 提交于 2019-12-23 16:24:54

问题


Both :checked and :selected seem to provide equal results when working with <option> elements. Is there any advantage to using one over the other? If :selected does the same thing as :checked, what is the reason for it to be included in jQuery at all?

Example:

<p class="p1">Select a value</p>
<p class="p2">Select a value</p>

<select>
    <option value="a">Option one</option>
    <option value="b">Option two</option>
</select>


$('select').on('change', function(){

    $('.p1').text(function() { 
        return $('option:selected').text();
    });

    $('.p2').text(function() { 
        return $('option:checked').text();
    });
});

JS Bin demo


回答1:


Judging by the documentation, it seems that :selected is identical to :checked with the exception that it only matches option elements. This is corroborated by HTMLOptionElement being the only element type in the DOM to have a selected property (which is what :selected uses to test the selectedness of an element). In other words, when you're only interested in option elements, both selectors are identical — except :selected is non-standard.

Since the documentation itself recommends using standard selectors to maximize performance (and because why would you not use a standard selector over a non-standard one if given the choice?), I don't think there is any reason to use :selected in any situation ever. I can't think of any situation in which *:selected would be preferable to option:checked (seriously, when was the last time you used a pseudo-class of this kind without a type selector?).

Perhaps the reason it was included in jQuery was because Selectors 3 (in which :checked appears) wasn't yet standardized at the time jQuery was born, but :checked has been in the spec since 2000, so I'm not entirely convinced that's really the reason.




回答2:


Normally, :selected is for SELECT OPTIONS elements. :checked is for CHECKBOX elements.

<p class="p1">Select a value</p>
<p class="p2">Select a value</p>
  <p class="p3">Select a value</p>
  <p class="p4">Select a value</p>

<select>
<option value="a">Option one</option>
<option value="b">Option two</option>
</select>

  <input type="checkbox" value="C" />


$('input').on('change', function(){

  $('.p1').text(function() { 
    return $('option:selected').text();
  });

  $('.p2').text(function() { 
    return $('option:checked').text();
  });

  $('.p3').text(function() { 
    return $('input[type="checkbox"]:selected').val();
  });

   $('.p4').text(function() { 
    return $('input[type="checkbox"]:checked').val();
  });
});

http://jsbin.com/zadocokule/edit?html,js,output



来源:https://stackoverflow.com/questions/44088774/difference-between-checked-and-selected-when-working-with-option-elements-in-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!