简体   繁体   English

如何使用 jQuery 将文本添加到特定的 div 元素?

[英]How do I add text to specific div element using jQuery?

I am having a problem with jquery.我在使用 jquery 时遇到问题。 My HTML is我的 HTML 是

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

Now I am trying to add text in span using Jquery.现在我正在尝试使用 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>

How can I do that in jquery?我怎样才能在 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");

The second and last one likely being the fastest because they target particular container by ID.第二个和最后一个可能是最快的,因为它们通过 ID 定位特定容器。
(internal jQuery optimisations may prove me wrong with any future version) (内部 jQuery 优化可能会证明我对任何未来版本都是错误的)

Performance comparison性能对比

Here's a JSPerf test that performance compares upper possibilities.这是一个JSPerf 测试,性能比较了较高的可能性。 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.我试过在 Chrome 上运行它们,如果你想看到差异,你可以在其他浏览器中运行它们。

$('#first span.test').text('Welcome');

jQuery selectors are CSS selectors extended with a bit of magic. jQuery 选择器是用一些魔法扩展的 CSS 选择器。 You can find everything you need to know here: http://api.jquery.com/category/selectors/你可以在这里找到你需要知道的一切: http : //api.jquery.com/category/selectors/

You need to use the :first selector to say that you only want to add text to the first element the selector finds.您需要使用:first选择器来表示您只想将文本添加到选择器找到的第一个元素。 Try this:试试这个:

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

Example fiddle示例小提琴

Alternatively, you can use the id of the parent div to make the selector unique:或者,您可以使用父 div 的id使选择器唯一:

$j('#first .test').text('Welcome');

In this example you can do what RoRyMcCrossan For general selection i recommend you to look at this : http://api.jquery.com/child-selector/在这个例子中,你可以做 RoRyMcCrossan 对于一般选择我建议你看看这个: http ://api.jquery.com/child-selector/

Or you can use this或者你可以使用这个

http://api.jquery.com/eq-selector/ http://api.jquery.com/eq-selector/

由于您有一个 ID,它通常在一页上是唯一的,因此最好使用以下内容:

$("#first span.test").text("Welcome");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM