创建后获取html元素 [英] get the html element after created
问题描述
当我单击输入时,我正在创建一个img,然后从创建的img中获取html或其他任何内容.
i'm creating a img when i click in a input, then i get the html or anyelse from the created img.
但是我不知道为什么这不起作用!
but i dont know why this is not working!
总是返回null
我的js:
$("#click").click(function(){
var $imgDone = $('<img/>').attr('src', 'someImage/insomewhere.jpg');
$(this).after($imgDone);
setTimeout(function(){
alert($(this).next().html());
}, 1000);
});
我负责实验: 演示
i mande a exp.: Demo
推荐答案
this
指向setInterval
中的错误位置.
您在外部作用域中拥有的this
与您在回调内部获得的this
不同,后者通常是window
对象,因为:
The this
you have in the outer scope isn't the same as the this
that you get inside the callback, which will usually be the window
object, since:
setInterval(f, t)
实际上是
window.setInterval(f, t);
要解决此问题,请在外部范围中复制this
的副本:
To solve the problem, take a copy of this
in the outer scope:
$("#click").click(function(){
var self = this;
var $imgDone = $('<img/>').attr('src', 'someImage/insomewhere.jpg');
$(this).after($imgDone);
setTimeout(function(){
alert($(self).next().html());
}, 1000);
});
为了提高效率,如@ T.J. Crowder建议,您实际上可以使用jQuery构造函数来获取该副本,并为自己节省一些对jQuery的调用:
For efficiency, as @T.J. Crowder suggests, you could actually use the jQuery constructor to take that copy, and save yourself a few calls to jQuery:
$("#click").click(function(){
var $this = $(this);
var $imgDone = $('<img/>')
.attr({src: 'someImage/insomewhere.jpg'})
.insertAfter(this); // NB: not $this here
setTimeout(function(){
alert($this.next().html());
}, 1000);
});
另一个问题是.html()
显示标签的 inner 内容,而不是标签本身,并且您的img
标签没有内部内容.
The other problem is that .html()
shows the inner contents of tags, not the tags themselves, and your img
tag has no inner contents.
似乎没有任何内置的jQuery方法可返回元素的实际整个HTML.为此,您需要将元素放入其他内容(例如<div>
),然后使用那个的.html()
.
There doesn't appear to be any builtin jQuery method that returns the actual whole HTML of an element. To do that you'd need to put your element into something else (e.g. a <div>
) and then take the .html()
of that.
Here's a plugin I just made that does this, inspired by something I found via Google:
(function($) {
$.fn.outerhtml = function() {
return $('<div/>').append(this.clone()).html();
};
})(jQuery);
针对您的问题的演示,位于 http://jsfiddle.net/alnitak/qaSmS/
Demo of it in use on your problem at http://jsfiddle.net/alnitak/qaSmS/
这篇关于创建后获取html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!