为什么 jQuery 会删除我的 DIV 中的内容以及如何阻止它这样做?
这是我的 sandbox.php 文件中的一些代码:
<div class="jq">
<img class="active" id="also" alt="Fifty-Fifty?" src="http://placehold.it/350x150"/>
</div>
<div id="title">
This is the alt element of the 350x150 image, found by class. It should return 'Fifty-Fifty?':
<script>
$("#title").text($('.jq .active').attr('alt'));
</script>
</div>
所以,我只是想弄清楚为什么“这是 alt 元素...”被删除,我想知道如何防止这种情况发生。我实际上并不觉得我需要一个“标题”div。我觉得我可以将文本附加到“jq”部分。
有人可以解释为什么人们也对结构文档感兴趣吗?我正在查看 StackOverflow 的代码,他们将所有链接都放在该 div 的 hlinks-custom
-id'd div 中。锚点使其结构分隔变得非常清晰,并且似乎不需要更多的东西。不过,转到 YouTube.com,您会看到页面上的每个链接都有自己的 div。这看起来不奇怪吗?
Here's some code I've got in my sandbox.php file:
<div class="jq">
<img class="active" id="also" alt="Fifty-Fifty?" src="http://placehold.it/350x150"/>
</div>
<div id="title">
This is the alt element of the 350x150 image, found by class. It should return 'Fifty-Fifty?':
<script>
$("#title").text($('.jq .active').attr('alt'));
</script>
</div>
So, I'm just trying to figure out why "This is the alt element..." gets scrubbed, and I want to know how to keep that from happening. I actually don't feel that I need a 'title' div. I feel like I could just append the text into the 'jq' section.
Could someone explain why people over structure documents, also? I'm looking at the code for StackOverflow, and they put all of the links in their hlinks-custom
-id'd div in that div. The anchors make it very clear structural separator, and it doesn't seem anything more is needed. Go to YouTube.com, though, and you'll see that every single link on the page has its own div. Does that not seem strange?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我会使用
.append()
,如下所示:这是一个 JSFiddle。
I would use the
.append()
, like so:Here is a JSFiddle.
因为你是替换,而不是附加。尝试:
Because you're replacing, not appending. Try:
这应该可以解决您的问题 -
text
函数将替换所选元素中的所有文本内容。因此,您需要将原始文本附加到要添加的文本中,然后将所有内容传递给text
函数。This should fix you problem -
The
text
function will replace all text content within the selected element. So you need to append the original text to the text you want to add, then pass all of that to thetext
function.您正在设置标题 div 的文本,因此您可以清除它并再次设置它。您正在寻找 jquery append() 函数。
You are setting the text of the title div so you are in affect clearing it and setting it again. You are looking for the jquery append() function.
.text(value)
方法将 div 的内容设置为value
。因此,之前 div 中的内容将被删除,以便为新内容腾出空间。您可能想改用
.append(value)
方法。它将值附加到 div 内容的末尾。The
.text(value)
method sets the content of the div to thevalue
. Therefore, what was in the div before is removed to make room for the new content.You may want to use the
.append(value)
method instead. It appends the value to the end of the div's content.