[英]Getting undefined even though it is defined ( JavaScript )
嘗試編寫基本的jQuery插件:
<textarea>
<p>Hello World!</p>
</textarea>
$.fn.wysiwyg = function (options) {
var e = $(this).replaceWith("<iframe>");
console.log($(this)[0].contentDocument);
};
$("textarea").wysiwyg();
var e = $(this).replaceWith("<iframe>");
console.log($(this)[0].contentDocument);
我在控制台上變得undefined
。 如果我為此iframe設置一個id屬性,並在console.log
方法中將該id
作為目標,則它可以正常工作,但是我想使用$(this)
。 為此可以做什么?
問題是this
仍然會引用textarea
因此
$.fn.wysiwyg = function (options) {
var $frame = $("<iframe>")
var e = $(this).replaceWith($frame);
console.log($frame[0].contentDocument);
};
演示: 小提琴
嘗試這個:
$.fn.wysiwyg = function (options) {
var $e = $("<iframe>");
this.replaceWith($e);
console.log($e);
};
$("textarea").wysiwyg();
:: JsFiddle ::
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.