我用什么选择器来访问这个div?

时间:2015-02-05 11:15:23

标签: javascript jquery

如果我有这样的结构:

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
);

如何定位包含文本some more text的div并用新文本替换该文本?

我已将其存储在名为myThing的变量中,但我不知道如何向下导航到我想要的div。

我不能将这些类用作选择器,因为我的应用程序中存在多个此变量的实例。

也许这样的事情?哪个不起作用......

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

4 个答案:

答案 0 :(得分:5)

你停止疯狂的嵌套,并使用变量

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');

答案 1 :(得分:0)

不确定,但也许:

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

答案 2 :(得分:0)

试试这个,

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

According to Jquery Documentation它会根据它的内容选择div

希望这有帮助。

答案 3 :(得分:0)

您的代码中有错误(可能是因为复杂的嵌套)。检查这个小提琴http://jsfiddle.net/r1h8fy9j/,找出纠正的问题的一个和两个可能的解决方案:

jQuery(myThing).find('div:last').text('text to replace to'); - 如果目标div是最后一个。

jQuery(myThing).find('div').eq(1).text('text to replace to'); - 如果目标div在特定索引处。