gpt4 book ai didi

javascript - 使用 # 和 . 安全吗? html属性中的字符?

转载 作者:搜寻专家 更新时间:2023-10-31 08:33:11 28 4
gpt4 key购买 nike

我想知道是否可以将 HTML 对象的属性值设置为包含 # 字符的字符串?

我想这样做的原因是页面会有很多项目应该将页面滚动到指定的元素,我想存储数据'它应该滚动到哪个项目? ' 作为数据滚动属性。

所以我的 JavaScript 代码 - 将 - 如下所示:

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));
});

所以 html 元素看起来像:

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

安全吗?

作为附带问题,为什么

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

不工作但是

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

有效吗?

最佳答案

根据 W3C 规范,是的,使用 U+0023 NUMBER SIGN安全的字符 ( # ) 和 U+002E FULL STOP字符 ( . )。

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.

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

关于javascript - 使用 # 和 . 安全吗? html属性中的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18597760/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com