简体   繁体   中英

Is it safe to use # and . characters in html attributes?

I'm wondering if I can set the value of an HTML object's attribute as a string that contains # character ?

The reason I want to do this is the page will have a lot of items that should scroll the page to specified elements, and I want to store the data ' which item should it scroll to? ' as a data-scrollto attribute.

So my JavaScript code -will- look like this:

function ScrollToElement(lm)
{
    var theTop  = lm.offset().top;
    $("html,body").animate({
        scrollTop: theTop/*,
        scrollLeft: 1000*/
    });
}

// .. and add click event to all such objects : 
$('.scroller').click(function(){
        var theSelector = $(this).attr('data-scrollto');
        ScrollToElement($(theSelector));
    });

so the html elements will look like :

<a class='scroller' data-scrollto='p#p-to-scroll'>Click to scroll to p</a>

is it safe ?

And as a side question, why does

$(element).data('scrollto');

does not work but

$(element).attr('data-scrollto'); 

works ?

According to the W3C specs, yes, it is safe to use the U+0023 NUMBER SIGN characters ( # ) and the U+002E FULL STOP characters ( . ).

The attribute name, followed by zero or more space characters, followed by a single U+003D EQUALS SIGN character, followed by zero or more space characters, followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal space characters, any U+0022 QUOTATION MARK characters ( " ), U+0027 APOSTROPHE characters ( ' ), U+003D EQUALS SIGN characters ( = ), U+003C LESS-THAN SIGN characters ( < ), U+003E GREATER-THAN SIGN characters ( > ), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string .

Read http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#attributes-0 .

Yes, you can store a hash # and . in the data attributes. You should use the proper data methods. http://api.jquery.com/jQuery.data/

var theSelector = $(this).data('scrollto');

If you can't seem to use the data method, check the version of jQuery you are using, it was introduced in version 1.2.3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM