如何在jQuery中替换('something')之后获取对象的实际内容
-
01-10-2019 - |
题
我有这个代码
$(document).ready(function(){
$('.selector').click(function(){
obj = $(this);
obj.replaceWith('<div class="size">whats up man ??!</div>');
alert(obj.html());
});
});
我想获得已被“替换”的“ OBJ”的新内容
但,
我得到了旧内容...
我如何获得“ obj”的实际内容???
我的目的是访问新的“ OBJ”
$('.selector').click(function(){
var obj = $(this),
repl = $('<div class="size">whats up man ??! <span class="medium"></span></div>');
obj.replaceWith(repl);
alert(obj.find('span').attr('class')); //this will print 'undefined'
});
我想打印“跨度”的类名称为“中等”
解决方案
您更新的方法是正确的方法,只需要这样的调整:
$('.selector').click(function(){
var obj = $(this),
repl = $('<div class="size">whats up man ??! <span class="medium"></span></div>');
obj.replaceWith(repl);
alert(repl.find('span').attr('class'));
});
您可以在这里测试. 。重要的改变是 repl.find()
查看新元素而不是旧元素。
其他提示
你为什么要这样做?您知道您替换了什么...
$(document).ready(function(){
$('.selector').click(function(){
var obj = $(this);
var replacement = $('<div class="size">whats up man ??!</div>');
obj.replaceWith(replacement);
alert(replacement.html());
});
});
不隶属于 StackOverflow