Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/468.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用jQuery将文本添加到特定的div元素?_Javascript_Jquery_Html - Fatal编程技术网

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

Javascript 如何使用jQuery将文本添加到特定的div元素?,javascript,jquery,html,Javascript,Jquery,Html,我对jquery有问题。我的HTML是 <div id="first"> <span class="test"></span> </div> <div id="second"> <span class="test"></span> <div> 之后就变成了, <div id="first&q

我对jquery有问题。我的HTML是

<div id="first">
   <span class="test"></span>
</div>
<div id="second">
   <span class="test"></span>
<div> 
之后就变成了,

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

欢迎
欢迎
但是,我正在努力实现的是

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

欢迎

在jquery中如何才能做到这一点?

您需要使用
:first
选择器来表示您只想向选择器找到的第一个元素添加文本。试试这个:

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

或者,您可以使用父div的
id
,使选择器唯一:

$j('#first .test').text('Welcome');
jQuery选择器是CSS选择器,具有一点魔力。你可以在这里找到你需要知道的一切:

几种可能的选择 其他人已经提供了他们的答案,但让我给你一些更多的选择

$("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优化可能会证明我对任何未来版本都是错误的)

性能比较
这里有一个性能比较高的可能性。正如预期的那样,第二种和最后一种方法是最快的,因为元素选择非常简单。我试过在Chrome上运行它们,如果你想看到它们的不同,你可以在其他浏览器上运行它们。

在这个例子中,你可以做Rorymcrossan做的事情 对于一般选择,我建议您查看以下内容:

或者你可以用这个


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

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

@RobertKoritnik说他的代码是有效的,我假设他使用
var$j=jQuery.noConflict()创建了一个新的jQuery别名
我没有投票,但是
:first
选择器筛选器匹配作为其父代的第一个孩子的所有元素,这意味着所有
测试
div仍将匹配。。。所以你的第一个解决方案当然是无效的。如果你做
$(“span.test”).first()…
@RobertKoritnik你正在与
:first
:first child
合作,那就没问题了<代码>:first选择匹配集的第一个元素。@RoryMcCrossan:你说得对。。。我的错。。。但正如前面提到的,我没有投票,所以我不能删除它。@RobertKoritnik别担心,没问题:)嗯,如果不是jQuery的OP看起来很新的话,我不会这么固执。我在想象各种可怕的代码被编写:)
$("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");
$("#first span.test").text("Welcome");