1

基本的には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を使用して変更する必要があるデータを変更するにはどうすればよいですか? 明らかに、サーバーへのアクセス権がありません。

foo の 1 は常に乱数であり、推測できないため、コードは $(this) で開始する必要があります。コードが含まれる投稿に基づいて、コードはすべての投稿で機能する必要があります。

通常のネスティングを使用できれば、そうします。
コードは
$(this).sibling('.intro').child('.bar').text('bar'); のようになります。

4

7 に答える 7

4

WORKING FIDDLE -- セレクターのチェーン

ネスティングの目的で、次のように選択します。

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

上記のコードは、bar が intro 内にあり、intro が foo1 内にあることを示しています。

それでも疑問がある場合は、これを参照してください->ネストされたセレクター

他の人が示唆したように、

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

これは、ネスティングにアプローチするための完璧な方法でもあります。

于 2013-07-26T09:58:58.820 に答える
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")

要点はお分かりだと思います...質問を拡大しない限り、適切な回答を提供することはできません

于 2013-07-26T09:57:22.283 に答える
0

私の質問に対する正しい答えは結局

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

ご助力いただきありがとうございます :)

于 2013-07-26T14:37:51.293 に答える
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ある場合はより安全です。

于 2013-07-26T09:58:01.837 に答える
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 要素が配置されていることを確認してください。

于 2013-07-26T09:58:43.717 に答える
0

あなたが使用することができます-

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

参照

于 2013-07-26T10:07:14.313 に答える