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

标签 javascript jquery html scroll

我想知道是否可以将 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/

相关文章:

javascript - 如何从 Angularjs 内联模板脚本标记内打印到 console.log?

jquery - 更改 div :after border right color by jQuery

javascript - angularJS 使用 Angular 谷歌地图查找位置/地名

php - 在不使用 SSL 的情况下防止数据包嗅探的最佳方法是什么?

javascript - 表单对象中的换行符

javascript - js 弹出窗口打开并在另一个页面上检查其状态

jquery - 网站导航 - 向下滑动页面内容 - 类似于示例站点 'pavilionvenue.co.uk' 但水平

javascript - 淡出不是函数 jquery 3.3.1

html - CSS 与 DRY

javascript - 如何通过#ID 100% AngularJS 获取元素 SELECT 中的文本和值