Setting a boolean attribute with jquery

后端 未结 3 1158
离开以前
离开以前 2021-01-17 10:40

I understand that jquery will allow you to modify attributes with the .attr() method. There are basically two methods:

$(\'#element\').attr(\'attribute\', \'         


        
相关标签:
3条回答
  • 2021-01-17 11:26

    Try using .prop to deal with boolean that is for supported attributes like selected/disabled/checked e.t.c

    $('#element').prop('attribute', true);
    

    from jQuery docs, (an example)

    elem.checked returns true (Boolean) Will change with checkbox state

    $(elem).prop("checked") returns true (Boolean) Will change with checkbox state

    elem.getAttribute("checked") returns "checked" (String) Initial state of the checkbox; does not change

    $(elem).attr("checked")(1.6) returns "checked" (String) Initial state of the checkbox; does not change

    $(elem).attr("checked")(1.6.1+) returns "checked" (String) Will change with checkbox state

    $(elem).attr("checked")(pre-1.6) returns true (Boolean) Changed with checkbox state

    0 讨论(0)
  • 2021-01-17 11:35

    HTML attributes are always string values. If you indeed want to set something other than a string, then please consider using jQuery.data()

    0 讨论(0)
  • 2021-01-17 11:40

    I use this method in jQuery

    jQuery('option').attr("selected", "");
    

    or in JavaScript:

    document.querySelector("option").setAttribute("selected", "");
    

    It's just you need to pass an empty string to just set boolean attribute.

    0 讨论(0)
提交回复
热议问题