How to add an HTML attribute with jQuery

后端 未结 7 715
无人及你
无人及你 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:38

    Let me see if I understood you. You have, for example, the code:

    <a id="previous" href="#"></a>
    

    And by jQuery you want it to be:

    <a id="previous" control="-6" href="#"></a>
    

    Is it right? If it is. You just have to do:

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

    If an attribute doesn't exists it's created by jQuery. So, to remove it you can do:

    $('#previous').removeAttr('control');
    

    What you're doing doesn't respect the html rules and everything else, but it works fine, a lot of plugins do the same. ;D

    I hope this could be helpful!

    See you!

    0 讨论(0)
  • 2020-12-03 11:47
    $("#previous").attr("control", "-6");
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-03 11:55

    Since the jQuery version has been well covered here, I thought I'd offer something different, so here a native DOM API alternative:

    document.getElementById('previous').setAttribute('control','-6');
    

    Yes, I know you asked for jQuery. Never hurts to know the native way too. :o)

    0 讨论(0)
  • 2020-12-03 11:56

    Try this:

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

    Why? the $.attr(); function of jQuery allows you to add, get or update attributes (class, id, href, link, src, control and everything else!).

    0 讨论(0)
  • 2020-12-03 11:59

    jQuery's attr will do that. Example:

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

    Also check out this example at http://jsfiddle.net/grfSN/.

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