javascript - 创建一个带有名为 offset 的属性的 anchor

标签 javascript jquery

使用以下代码动态创建 anchor 时,我遇到了非常奇怪的行为:

var newAnchor = $('<a>', {
                    'href': '#',
                    'class': 'seeMoreFromSection load-multi',
                    'offset':'12',
                    'type': '15',
                    'sec': '4'
                }).html('See more');

$('a.seeMoreFromSection').replaceWith(newAnchor);

问题出在名为 offset 的属性中,它会导致以下错误:无法使用 'in' 运算符在 12 中搜索 'using'。当我删除行 'offset':'12' 时,一切正常。 我通过在创建 anchor 后添加此属性来使其工作:

$('a.seeMoreFromSection').attr('offset', '12');

但我仍然不明白问题出在哪里,是某种保留字还是什么?

更新:浏览器 Google Chrome 33.0.1750.154 m

最佳答案

正如documentation中所示,您可以使用有效的 HTML 属性、有效的事件类型和一些 jQuery 方法(offset() 是其中之一):

If the second argument is passed, the HTML string in the first argument must represent a a simple element with no attributes. As of jQuery 1.4, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset.

offsettypesec 无论如何都不是有效的 HTML 属性,因此您不能指望您的工具接受它们。您可以使用 data- 属性来使您的特殊属性有效,也可以使用 data() jQuery 方法,除非您特别需要将数据存储在 HTML 属性中(大多数情况下并非如此)。

关于javascript - 创建一个带有名为 offset 的属性的 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22786028/

相关文章:

jquery - ASP.NET MVC 的基本 AJAX 示例?

jQuery - 在新窗口中打开 id 中的所有链接

javascript - 使用 javascript 在单击按钮时逐字突出显示句子中的文本

javascript - 如何在同一个 Angular JS 应用程序中使用具有不同身份验证 header 的不同 API

Javascript处理2数据属性

javascript - 在 D3 树中添加鼠标悬停时的文本

javascript - 避免 javascript 警告 - Vue js 解决方案的实现

javascript - 在我的脚本中无法根据 boolean 值更新 DOM

javascript - 在javascript中的文本之间创建空间

javascript - 如何在网页中固定滚动?