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

查看:142
本文介绍了我如何使用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');

之后,它变成了,

After that it becomes,

<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?

感谢

Thanks

推荐答案

几种可能的替代方案



答案已经存在,但让我给你更多的选择。

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天全站免登陆