簡體   English   中英

即使已定義也變得未定義(JavaScript)

[英]Getting undefined even though it is defined ( JavaScript )

嘗試編寫基本的jQuery插件:

HTML:

<textarea>
    <p>Hello World!</p>
</textarea>

jQuery的:

$.fn.wysiwyg = function (options) {

    var e = $(this).replaceWith("<iframe>");
    console.log($(this)[0].contentDocument);

};
$("textarea").wysiwyg();

JSFIDDLE示范

問題

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM