jQuery DOM 元素创建与innerHTML

发布于 2024-09-05 13:19:39 字数 533 浏览 1 评论 0原文

在回答我的一个问题时,cletus提到 在 jQuery 中创建元素时,最好使用直接创建 DOM 元素,而不是innerHTML。我尝试用谷歌搜索,但找不到一篇有比较的好文章。

我在下面提供了这段代码作为示例,我想知道是否有人可以帮助我以直接 DOM 元素创建形式重写它,希望我以后也能了解其中的区别。

var img = $(this);
img.append('<p class="cap"><a href="'+img.parent().attr('href')+'">'+
img.attr('title')+'</p></a>');

非常感谢。

While having one of my questions answered, cletus mentioned that when creating elements in jQuery it's better to use direct DOM element creation, instead of innerHTML. I tried googling it but I wasn't able to find a good article with comparisons.

I've provided this code bellow as an example and I was wondering if someone could help me rewrite it in direct DOM element creation form in hope that i would also learn the difference afterwards.

var img = $(this);
img.append('<p class="cap"><a href="'+img.parent().attr('href')+'">'+
img.attr('title')+'</p></a>');

Thanks so much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

山有枢 2024-09-12 13:19:39

是的,避免使用 HTML 字符串。您给自己带来了错误和潜在的跨站点脚本安全漏洞。例如:

'<a href="'+img.parent().attr('href')+'">'

如果父级 href 中的 URL 包含此 HTML 上下文中的特殊字符(例如 <"&? 最好的情况是您会得到无效的标记,这可能会导致浏览器出错;最坏的情况是,如果 URL 来自用户提交,则会出现安全问题

(好的,<) 。和 " 不太可能出现在 URL 中,但 & 确实很有可能出现。您在文本内容中放入的 title 可能会出现在 URL 中。变得更加脆弱。)

这是一个大且日益严重的问题。正如我们开始解决来自服务器端模板的 HTML 注入错误(例如 PHP 用户忘记 htmlspecialchars()),我们现在引入了加载使用 innerHTML 和 jQuery 的 html() 进行简单的 HTML 黑客攻击,从而产生新的客户端 XSS。避免。

可以手动转义插入到 HTML 中的文本:

function encodeHTML(s) {
    return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}

'<a href="'+encodeHTML(img.parent().attr('href'))+'">'

但实际上,您最好使用直接 DOM 样式的属性和方法,因为它们不涉及 HTML 解析,所以不需要任何逃脱。它们被称为 DOM 风格,因为这是原始 DOM Level 1 HTML 功能的工作方式(早在 innerHTML 露出丑陋的头之前就已经存在了):

var a= document.createElement('a');
a.href= this.parentNode.href;
a.appendChild(document.createTextNode(this.title));

在 jQuery 中,您使用 attr() 和 text() 来执行相同的操作:

var a= $('<a></a>');
a.attr('href', $(this).parent().attr('href');
a.text($(this).attr('title'));

在 jQuery 1.4 中,您可以使用元素创建快捷方式最方便地完成此操作:

$(this).append(
    $('<p class="cap"></p>').append(
        $('<a></a>', {
            href: $(this).parent().attr('href'),
            text: $(this).attr('title')
        })
    )
);

但这看起来仍然有点可疑,您的父级是什么从哪里获取 href?在链接内放置

或其他链接是无效的。

Yeah, avoid HTML string-slinging. You're giving yourself bugs and potentially cross-site scripting security holes. For example:

'<a href="'+img.parent().attr('href')+'">'

what if the URL in the parent's href contains characters that are special in this HTML context, like <, " or &? At best you'll get invalid markup that might trip the browser up; at worst, if the URL comes from user submission, a security problem.

(OK, < and " are unlikely to appear in a URL, but & is very likely indeed. The title you're putting in the text content may be more vulnerable.)

This is a large and increasing problem. Just as we're starting to get a handle on fixing the HTML-injection bugs coming from templating on the server-side (eg. PHP users forgetting to htmlspecialchars()), we're now introducing loads of new client-side XSS from naïve HTML-hacking with innerHTML and jQuery's html(). Avoid.

You can escape text you're inserting into HTML manually:

function encodeHTML(s) {
    return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}

'<a href="'+encodeHTML(img.parent().attr('href'))+'">'

but really, you're better off using the direct DOM-style properties and methods, which, since they involve no HTML parsing, don't require any escaping. They're called DOM-style because that's the way the original DOM Level 1 HTML features work (which existed back before innerHTML reared its ugly head):

var a= document.createElement('a');
a.href= this.parentNode.href;
a.appendChild(document.createTextNode(this.title));

In jQuery you use attr() and text() to do the same:

var a= $('<a></a>');
a.attr('href', $(this).parent().attr('href');
a.text($(this).attr('title'));

And in jQuery 1.4, you can do it most conveniently using an element creation shortcut:

$(this).append(
    $('<p class="cap"></p>').append(
        $('<a></a>', {
            href: $(this).parent().attr('href'),
            text: $(this).attr('title')
        })
    )
);

This still looks a bit questionable though, what's the parent that you're getting the href from? It's invalid to put a <p>, or another link, inside a link.

拥醉 2024-09-12 13:19:39

这就是在 jQuery 中创建元素的方式:

var myDiv = $('<div class="my-class"></div>');

然后您可以使用 myDiv 做各种很酷的事情。

这是使用您的示例:

var img = $(this);
var myP = $('<p class="cap"></p>');
var myA = $('<a></a>');
myA.attr("href",img.parent().attr('href'));
myA.html(img.attr('title'));
myP.append(myA);
this.append(myP);

这有点冗长,但是是的。

This is how you create elements in jQuery:

var myDiv = $('<div class="my-class"></div>');

And then you can do all kinds of cool stuff with myDiv.

Here it is using your example:

var img = $(this);
var myP = $('<p class="cap"></p>');
var myA = $('<a></a>');
myA.attr("href",img.parent().attr('href'));
myA.html(img.attr('title'));
myP.append(myA);
this.append(myP);

It's a bit verbose, but yeah.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文