我正在寻找一种解决方案,使用与编译语言中的#ifndef 完全相同的方式在 Javascript 中仅定义一次函数。我找到了几个本应模仿此功能的库,但它们不起作用。
我正在使用 MVC 3 Razor 并定义了一些 html 助手,它们确实将本质上是用户控件的内容放到了页面上。
每个控件都有一组为该控件定义特定功能的 javascript 函数,因此问题就在这里:当在单个页面上多次调用助手时,函数会被定义多次。
我希望找到一种方法来保留在助手中定义的非常少量的 javascript,而不必将这些小助手中的每一个的所有 javascript 划分在一个单独的文件中。
示例:
@helper CmsImage(int id)
{
var Html = ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html;
<text>
<input type="button" class="editor_function" style="display: none;" onclick="editImage(@id); return false;" />
<script>
function editImage(id) {
$('#alt_text' + id).attr('value', $('#' + id).attr('alt'));
$('#image_url' + id).attr('value', $('#' + id).attr('src'));
}
function saveImage(button, id) {
$(button).parent().parent().removeClass('color-yellow').addClass('color-red');
$(button).parent().siblings('div.widget-content').html('<img alt="' + $('#alt_text' + id).val() + '" src="' + $('#image_url' + id).val() + '" id="' + id + '" />');
}
#endif
</script>
Image Url:
<input type="text" id="image_url@{id.ToString();}" /><br />
Alt Text:
<input type="text" id="alt_text@{id.ToString();}" /><br />
<input type="button" value="save" onclick="saveImage(this, @{id.ToString();});" />
@Html.Raw(GetCurrentContent(id))
</text>
}
以上在浏览器中不起作用,如果出现错误:'48: Unrecognized token ILLEGAL'
最佳答案
我想您知道,Javascript 没有像 C/C++ 这样的预处理器指令,但您可以使用在运行时评估的常规 if
语句,如下所示:
if (typeof myFunc === "undefined") {
var myFunc = function(a,b) {
// body of your function here
}
}
或者对于整个函数库:
if (!window.controlUtilsDefined) {
window.controlUtilsDefined = true;
// put control library functions here
function aaa() {
// body here
}
function bbb() {
// body here
}
}
或者如果您想根据其他变量进行检查:
var myFunc;
if (debugMode) {
myFunc = function(a,b) {
// body of your function here
}
} else {
myFunc = function(a,b) {
// body of your alternate function here
}
}
如果您只是担心每个控件使用的库中有多个完全相同的函数名称副本,那么从技术上讲,这在 Javascript 中不是问题。最后定义的将是可操作的,但如果它们都相同,那在技术上就不是问题。内存中将只存在一个定义,因为后面的定义将替换前面的定义。
如果您控制控件的源代码,那么最好将常用实用程序单独分解成它们自己的 JS 文件,并让主机页面只包含该实用程序脚本文件一次。
或者(稍微多一点工作,但对主机页面没有额外的责任),每个控件都可以从外部 JS 文件动态加载它们的实用程序,并检查一个已知的全局变量,看看是否有其他控件已经加载了公共(public)外部JS.
关于javascript - #ifndef 在 javascript 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7376131/