简体   繁体   English

我使用什么选择器访问该div?

[英]What selector do I use to access this div?

If I have a structure like this: 如果我有这样的结构:

var myThing = jQuery(
    jQuery('<div/>')
        .addClass('myTopDiv')
        .append(
            jQuery('<div/>')
                .text('some text')
                .addClass('mySecondDiv')
        ).append('<div/>')
            .text('some more text') // I WANT TO REPLACE THIS TEXT
);

How do I target the div which contains the text some more text and replace that text with new text? 如何定位包含some more text的div并将该文本替换为新文本?

I've stored it inside a variable called myThing , but I don't know how to navigate down to the div I want. 我已经将其存储在名为myThing的变量中,但是我不知道如何向下导航至所需的div。

I can't use the classes as selectors as there are multiple instances of this variable in my application. 我不能将这些类用作选择器,因为在我的应用程序中有此变量的多个实例。

Something like this perhaps? 大概是这样吗? Which doesn't work... 哪个不行...

jQuery(
    jQuery('<tr/>')
        .text('new text')
).appendTo(myThing);

You stop the crazy nesting, and use variables 您停止疯狂的嵌套,并使用变量

var topDiv = $('<div />', {
                'class' : 'myTopDiv'
             }),
    secDiv = $('<div />', {
                'class' : 'mySecondDiv',
                text    : 'some text'
             }),
    thrDiv = $('<div />', {
                text : 'some more text'
             });

topDiv.append(secDiv, thrDiv);

// change text

thrDiv.text('Some other text');

Not sure but maybe: 不确定,但也许:

jQuery('div.myTopDiv div:last').text()

?

Try this one, 试试这个

$( "div:contains('John')" )

According to Jquery Documentation it will select the div by it's content 根据Jquery文档 ,它将根据其内容选择div

Hope this helps. 希望这可以帮助。

You have an error in your code (probably because of complex nesting). 您的代码中有错误(可能是由于复杂的嵌套)。 check this fiddle http://jsfiddle.net/r1h8fy9j/ for corrected one and two possible solutions for your issue: 检查此提琴http://jsfiddle.net/r1h8fy9j/,以更正您的问题的一种和两种可能的解决方案:

jQuery(myThing).find('div:last').text('text to replace to'); - in case if target div is the last one. -如果目标div是最后一个。

jQuery(myThing).find('div').eq(1).text('text to replace to'); - in case if target div is at specific index. -如果目标div位于特定索引处。

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

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