如何使用jQuery向特定的div元素添加文本? [英] How do I add text to specific div element using jQuery?

查看:41
本文介绍了如何使用jQuery向特定的div元素添加文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用jquery时遇到问题.我的HTML是

I am having a problem with jquery. My HTML is

<div id="first">
   <span class="test"></span>
</div>
<div id="second">
   <span class="test"></span>
<div> 

现在,我正尝试使用Jquery在范围内添加文本.

Now I am trying to add text in span using Jquery.

$j('span.test').text('Welcome');

它变成了

<div id="first">
    <span class="test">Welcome</span>
</div>
<div id="second">
    <span class="test">Welcome</span>
<div> 

但是,我正在尝试实现,

But, I am tryting to achieve is,

<div id="first">
    <span class="test">Welcome</span>
</div>
<div id="second">
    <span class="test"></span>
<div>

如何在jquery中做到这一点?

How can I do that in jquery?

推荐答案

几种可能的选择

其他人已经提供了答案,但是让我给您更多选择.

Several possible alternatives

Others have provided their answers already but let me give you some more alternatives.

$("span.test:first").text("Welcome");
$("#first span.test").text("Welcome");
$("span.test").first().text("Welcome");
$("span.test").eq(0).text("Welcome");
$("span.test", "#first").text("Welcome");

第二个和最后一个可能是最快的,因为它们通过ID定位到特定的容器.
(内部jQuery优化可能会证明我在任何将来的版本中都是错误的)

The second and last one likely being the fastest because they target particular container by ID.
(internal jQuery optimisations may prove me wrong with any future version)

这是 JSPerf测试,它的性能比较了更高的可能性.正如预期的那样,第二个和最后一个方法是最快的,因为大大简化了元素选择.我已经尝试过在Chrome上运行它们,如果愿意,可以在其他浏览器中运行它们.

Here's a JSPerf test that performance compares upper possibilities. As anticipated, the second and last approaches are the fastest of all because element selection is much simplified. I've tried running them on Chrome and you may run them in other browsers if you want to and see differences.

这篇关于如何使用jQuery向特定的div元素添加文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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