How to add an HTML attribute with jQuery

后端 未结 7 765
无人及你
无人及你 2020-12-03 11:34

Well, I have this jQuery image slideshow that uses the attribute \"control\" inside an . Seeing how it didn\'t validate I searched for a way to add this attribute i

7条回答
  •  不知归路
    2020-12-03 11:50

    Use jQuery's attr function

    $("#previous").attr("control", "-6");
    

    An example

    // Try to retrieve the control attribute
    // returns undefined because the attribute doesn't exists
    $("#previous").attr("control");
    
    // Set the control attribute
    $("#previous").attr("control", "-6");
    
    // Retrieve the control attribute (-6)
    $("#previous").attr("control");
    

    See this example on jsFiddle


    You can alternatively use data function to store values on elements. Works the same way, for example:

    $("#previous").data("control"); // undefined
    $("#previous").data("control", "-6"); // set the element data
    $("#previous").data("control"); // retrieve -6
    

    Using data you can store more complex values like objects

    $("#previos").data("control", { value: -6 });
    ($("#previos").data("control")).value; // -6
    

    See a data example on jsFiddle

提交回复
热议问题