gpt4 book ai didi

javascript - 如何在外部 Javascript 中正确使用它?

转载 作者:行者123 更新时间:2023-12-02 18:41:58 26 4
gpt4 key购买 nike

我有两个 javascript 函数,只要我将它们保留在 head 标记的 HTML 中,它们就可以正常工作,但我想将它们移动到外部 javascript 文件中。

function uploadImageSB() {

Shadowbox.init({});

// shadowbox for image upload
Shadowbox.open({

content: 'photo.cgi?function=photo_upload',
player: 'iframe',
title: 'Image Upload',
height: 200,
width: 500,
options: {

onFinish: function () {

// get the iframe
var iframe = document.getElementById('sb-player');

var formName = 'photoForm';

// add an event listener to determine when the sb form is fully loaded
if (iframe.addEventListener) {
// use addEventListener for Safari, Chrome, Firefox
iframe.addEventListener("load", getTA(formName), true);
} else {
// use attachEvent for IE
iframe.attachEvent("onload", getTA(formName));
}
}
}
})
};

上面的 JavaScript 调用下一个函数:

function getTA(fn) {

// get the contents of the tinymce editor
var ed = tinymce.activeEditor;
var content = ed.save();

// dynamically create textarea
var ta = document.createElement('textarea');
ta.textContent = content;
ta.name = 'article';
ta.value = ta.textContent;

// get the iframe content
var iframeContent = this.contentDocument || this.contentWindow.document;

// append the textarea to the shadowbox form, but do not display it
var form = iframeContent.getElementById(fn);
form.appendChild(ta);
form.getElementsByTagName('textarea')[0].style.display = 'none';
};

我认为问题出在我在这里使用this:

var iframeContent = this.contentDocument || this.contentWindow.document;

但我不知道如何解决它。谢谢。

最佳答案

根据我的理解,当您也从头部调用时,您的代码不应该工作。问题在于您的以下代码。

            if (iframe.addEventListener) {
// use addEventListener for Safari, Chrome, Firefox
iframe.addEventListener("load", getTA(formName), true);
} else {
// use attachEvent for IE
iframe.attachEvent("onload", getTA(formName));
}

您正在调用 getTA(formName) 函数本身,因为它是在窗口上下文中调用的,所以您不会将 iframe 作为您的上下文,即 this。

要解决此问题,您需要将其作为监听器作为函数对象作为参数提供,如下所示。
编辑:使用闭包支持对多个实例使用相同的 fn。

                if (iframe.addEventListener) {
// use addEventListener for Safari, Chrome, Firefox
iframe.addEventListener("load", (function(){
return function(){
getTa.call(this, formName);
}
})(), true);
} else {
// use attachEvent for IE
iframe.attachEvent("onload", (function(){
return function(){
getTa.call(this, formName);
}
})());
}

应该可以了。

关于javascript - 如何在外部 Javascript 中正确使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16751548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com