Javascript 我应该使用什么选择器访问此div?
如果我有这样一个结构:Javascript 我应该使用什么选择器访问此div?,javascript,jquery,Javascript,Jquery,如果我有这样一个结构: var myThing = jQuery( jQuery('<div/>') .addClass('myTopDiv') .append( jQuery('<div/>') .text('some text') .addClass('mySecondDiv') ).append('<div/>'
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
);
不确定,但可能:
jQuery('div.myTopDiv div:last').text()
?停止疯狂的嵌套,并使用变量
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');
var topDiv=$(“”{
“类”:“myTopDiv”
}),
secDiv=$(''){
'class':'mysecondiv',
文本:“一些文本”
}),
thrDiv=$(''){
文字:“更多文字”
});
topDiv.append(secDiv,thrDiv);
//更改文本
文本(“其他文本”);
试试这个
$( "div:contains('John')" )
它将根据其内容选择div
希望这有帮助。您的代码中有一个错误(可能是因为复杂的嵌套)。检查此提琴,以获得针对您的问题的正确的一种和两种可能的解决方案:
jQuery(myThing).find('div:last').text('text to replace to')代码>-如果目标div是最后一个
jQuery(myThing).find('div').eq(1).text('text to replace to')代码>-如果目标div位于特定索引处。共享HTML和正确/完整的jQuery代码我不能将这些类用作选择器!在这种情况下,一把小提琴会很有用:)如果他有100把这样的小提琴,那就用一个数组或者什么?为什么myThing.find('div:last')
不好?如果他有100个元素,这肯定比他目前正在做的要干净得多,除了大量的写作之外,这不是问题,但通常不应该使用javascript生成大量HTML。干杯,adeneo,这是一个比我更好的方法!非常感谢!
$( "div:contains('John')" )