我想知道是否可以检查我的DOM是否包含元素ID。实际上我动态加载我的模板(剑道模板)并将它们添加到我的身体中。
<body>
...
<script type="text/x-kendo-template" id="test-view">
...
</script>
</body>
此时我的加载脚本是
//Creates a gloabl object called templateLoader with a single method "loadExtTemplate"
var templateLoader = (function ($, host) {
//Loads external templates from path and injects in to page DOM
return {
//Method: loadExtTemplate
//Params: (string) path: the relative path to a file that contains template definition(s)
loadExtTemplate: function (path) {
//Use jQuery Ajax to fetch the template file
var tmplLoader = $.get(path)
.success(function (result) {
//On success, Add templates to DOM (assumes file only has template definitions)
var regSplit = new RegExp("[/\]+", "g");
var pathTab = path.split(regSplit);
var templateName = pathTab[pathTab.length - 1];
var regReplace = new RegExp("[.]+", "g");
var templateName = templateName.replace(regReplace, "-");
var s = $("<script type=\"text/x-kendo-template\" id=\"" + templateName + "\">" + result + "</script>");
$("body").append(s);
})
.error(function (result) {
alert("Error Loading Templates -- TODO: Better Error Handling");
})
tmplLoader.complete(function () {
//Publish an event that indicates when a template is done loading
$(host).trigger("TEMPLATE_LOADED", [path]);
});
}
};
})(jQuery, document);
在加载我的模板之前,我需要检查这个模板是否已经加载。我需要检查是否存在id =“test-view”的脚本。我怎么能这样做?
答案 0 :(得分:0)
var elementExists = (document.getElementById("elementId") !== null);
elementExists
现在将包含一个布尔值,告诉您该元素是否已存在。
答案 1 :(得分:0)
var element = $('#' + templateName)
if(!element.length) {
// create your template
}
答案 2 :(得分:0)
我建议添加
if(document.getElementById(templateName)) return;
后
var templateName = templateName.replace(regReplace, "-");
所以你的代码变成了:
.success(function (result) {
//On success, Add templates to DOM (assumes file only has template definitions)
var regSplit = new RegExp("[/\]+", "g");
var pathTab = path.split(regSplit);
var templateName = pathTab[pathTab.length - 1];
var regReplace = new RegExp("[.]+", "g");
var templateName = templateName.replace(regReplace, "-");
if(document.getElementById(templateName)) return;
var s = $("<script type=\"text/x-kendo-template\" id=\"" + templateName + "\">" + result + "</script>");
$("body").append(s);
})
答案 3 :(得分:0)
您可以使用长度或大小来执行此操作:
例如
$("#test-view").length //$("#test-view").size()
答案 4 :(得分:0)
使用jQuery:
if ($("#test-view").length) {...}
普通JavaScript:
if (document.querySelectorAll("#test-view").length) {...}
还有几条评论: