你可以使用jQuery来动态添加评论代码? [英] Can you use jquery to add comments dynamically to code?

查看:91
本文介绍了你可以使用jQuery来动态添加评论代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过:

I tried:

<script>
$(function() {
$('.class').before('<!--');
$('.class').after('-->');
});

</script>

但这并不适用于我未知的原因。

任何人都可以帮我理解为什么它不起作用,我会怎么做?谢谢,非常感谢。

but it didn't work for a reason unknown to me.

推荐答案

看起来你正在试图用 .class 消失。改为使用 .hide()。评论仅在浏览器第一次加载页面时被解析,因此添加评论不会评论某些内容。

解决方案

您需要了解HTML和DOM之间的区别。 HTML是页面的文本表示,但浏览器在页面加载时将其解析到DOM中。 JavaScript适用于DOM,而不适用于HTML。在DOM元素上使用 .innerHtml()来重新解析HTML。

It looks like you're trying to make objects with .class disappear. Use .hide() instead. Comments are only parsed when the browser first loads the page, so adding comments won't comment something out.

下面是使用 innerHtml()来隐藏使用HTML注释的元素的例子(但是请注意, em> never 做到这一点 - 我只是展示了如何做你看起来像你试图做的问题):

You need to learn the difference between HTML and the DOM. HTML is the textual representation of the page, but the browser parses it into the DOM on page load. JavaScript works on the DOM, not on the HTML. Using .innerHtml() on DOM elements reparses the HTML.

HTML:

HTML:


JavaScript(+ jQuery):

JavaScript (+ jQuery):

$(document).ready(function () {
    setTimeout(hideIt, 1000);
});

function hideIt() {
    $('div').html('<!--' + $('div').html() + '-->');
}​

这篇关于你可以使用jQuery来动态添加评论代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆