Html/[removed] Add Attribute to an HTML Control

前端 未结 5 555
悲哀的现实
悲哀的现实 2021-01-15 00:49

Need: Find a way to add a valid tag/attribute/property to a normal html control.

What I have is some javascript/jquery adding a click event to a link that will show

相关标签:
5条回答
  • 2021-01-15 01:16

    You can't get away with adding custom attributes to HTML elements whilst still being valid. It will generally work in current browsers, but it's a bit fragile in that if you happen to pick a name that is in use (now or in the future) as an HTML or JavaScript property by any browser, the clash will stop it from working.

    HTML5 proposes attributes whose names start with “data-​” as valid extension mechanisms. You could also consider namespaced elements in XHTML; this still isn't technically “valid XHTML” by the DTD but at least it is safe from collisions.

    <a href="..." class="showItLink" textToShow="This is the text to show">HI

    I suggest using the ‘title’ attribute for this particular purpose.

    0 讨论(0)
  • 2021-01-15 01:23

    If your textToShow attribute was an expando property, then this.textToShow would not return undefined, but since it is a custom attribute, you need to use jQuery's this.attr("textToShow") or the standard DOM this.getAttribute("textToShow").

    0 讨论(0)
  • 2021-01-15 01:30

    The best way to do this kind of thing is to hide the text in another element and then toggle that element. Try something like this:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
        <head>
            <title>clear test</title>
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js"></script>
            <script type="text/javascript">
                $(document).ready(function() {
                    $("#show-it").click(function() {
                        $("#message").toggle();
                    });
                });
            </script>
        </head>
        <body>
            <div>
                <a id="show-it" href="javascript:void(0);">show it</a>
                <div id="message" style="display:none;"> hidden message</div>
                hello world
            </div>
        </body>
    </html>
    
    0 讨论(0)
  • 2021-01-15 01:34

    The way you add an attribute to an html control is by using the element.setAttribute("attributeName", "attributeValue") where "element" is the element you want to add the attribute to.

    To get an attribute you use getAttribute("attributeName");

    0 讨论(0)
  • 2021-01-15 01:37

    If you're using JQuery, just get and set the attributes with .attr().

    Get: this.attr("textToShow")

    Set: this.attr("textToShow", value)

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