选择链

时间:2013-07-26 09:53:43

标签: javascript jquery

基本上,我必须使用jquery更改页面的一部分,但考虑到页面的格式,我对选择器链必须是什么感到非常困惑。

<span class="foo1">
 <span class="intro"><span class="bar">data I need to change</span></1>
 <span>...</span>
 <div class="body">This is the only place I can write code on the page</div>
</span>

如何使用jquery更改需要更改的数据?显然,我没有服务器访问权限。

代码必须以$(this)开头,因为foo中的1总是一个随机数,我猜不出来。根据代码所在的帖子,代码必须适用于所有帖子。

如果我可以使用正常的嵌套,我会的。
代码必须看起来像什么     $(本).sibling( '前奏。 ')子(' 巴。 ')文本(' 巴');

7 个答案:

答案 0 :(得分:4)

WORKING FIDDLE--CHAIN of Selectors

出于嵌套目的,您可以选择:

$('.foo1 >  .intro >  .bar').text("text to be changed");

上面的代码表明bar在intro中,intro在foo1里面。

如果您仍有疑问,请参阅此 - &gt; Nested selectors

正如其他人所说,

$('.foo1 .intro .bar').html("text to be changed");

这也是接近嵌套的完美方式。

答案 1 :(得分:3)

从你给出的小标记片段中,你可以这样做:

$(".bar").text("Whatever you want it to say instead");

但如果还有其他符合.bar的元素,则需要更具体:

// All of these would select that element
$(".intro .bar")
$(".foo1 .intro .bar")
$(".intro > .bar")
$(".intro:first-child .bar")

如果您需要相对于.body元素选择它:

// All of these would work
$(".body").siblings(".intro").find(".bar")
$(".body").parent().find(".bar")

我认为你明白了...... 除非你扩展你的问题,否则我们无法给你一个正确的答案

答案 2 :(得分:0)

如果我理解这个问题。

您只能在<div class="body">中添加代码。但是你想改变.bar中的文字

<span class="foo1">
 <span class="intro"><span class="bar">data I need to change</span></span>
 <span>...</span>
 <div class="body">
This is the only place I can write code on the page

<script type="text/javascript">
       $('.foo1 .intro .bar').html('Changed!'); 
</script>

</div>
</span>

您也可以$('.bar').html('Changed'),但如果您有多个span.bar更安全。

答案 3 :(得分:0)

这里:

<span class="foo1">
    <span class="intro"><span class="bar">data I need to change</span></1>
    <span>...</span>
    <div class="body">
        <script>
        $(document).ready(function() { // you need this to make sure document is loaded
            $('.foo1 .intro .bar').html("new text");
        });
        </script>
    </div>
</span>

你需要将你的js代码包装在

$(document).ready(function() { /* your code here */ });

或 - 如果在页面底部加载了jquery库:

window.onload = function () { /* your code here */ };

在尝试访问它们之前确保jquery和DOM元素已就位。

答案 4 :(得分:0)

http://jsfiddle.net/u4djZ/1

$('.foo1>.intro>.bar').text('Data Changed!');

正如MESSIAH指出的那样,你应该使用CSS child selector

答案 5 :(得分:0)

您可以使用 -

$(document).ready(function() { 
   $('.foo1 .intro .bar').html("new text");
});

Referance

答案 6 :(得分:0)

我的问题的正确答案最终成为了

<script class="12345">
$('.12345').parents('.foo').find('.intro>.bar').text('whatever');
</script>

感谢您的帮助:)