[英]How to Allow for document.getElementById to Not Find an ID?
I have an external JavaScript designed to replace certain words on my website. 我有一个外部JavaScript,旨在替换我网站上的某些单词。 To keep it efficient the same external script is loaded to every page so I can simply edit a single file if I need to make any changes. 为了保持效率,每个页面都加载了相同的外部脚本,因此如果需要进行任何更改,我可以简单地编辑一个文件。 This is a sample of the code I'm using: 这是我使用的代码示例:
document.getElementById("ey").innerHTML = 'AY'
document.getElementById("ny").innerHTML = 'BY'
document.getElementById("gy").innerHTML = 'CY'
However, I've discovered that if one page contains one element (say, "gy") but not another ("ny"), then the script fails to correctly execute. 但是,我发现,如果一个页面包含一个元素(例如,“ gy”)而不包含另一个元素(“ ny”),则该脚本将无法正确执行。 I have a long list of these changes (50ish), so I'd love to get it working. 我有一长串这些更改(50欧元),所以我很想让它生效。
Any idea how I can make the code provide allowances for not finding a particular id? 知道如何使代码提供未找到特定ID的余地吗?
well, you can write something like 好吧,你可以写类似
var el = document.getElementById("MY-ID")
if (el)
el.innerHTML = 'MY VALUE'
A nice solution is to wrap this in a method, like this: 一个好的解决方案是将其包装在一个方法中,如下所示:
function setValue(id, value){
var el = document.getElementById(id)
if (el)
el.innerHTML = value
}
And then call it like: 然后像这样调用它:
setValue('ey', 'AY')
setValue('ny', 'BY')
and so on 等等
setInnerHTML('ey', 'AY');
setInnerHTML('ny', 'BY');
...etc etc
function setInnerHTML(elementId, innerHTML) {
var el = document.getElementById(elementId);
if (el) {
el.innerHTML = innerHTML;
}
}
You could always make a small structure for this. 您总是可以为此做一个小结构。
(function(){
var defaultChanges = {
'ey' : 'AY',
'ny': 'BY',
'gy' : 'CY'
};
for(var id in defaultChanges){
var el = document.querySelector("#"+id);
if(el) el.innerHTML = defaultChanges[id];
}
})()
This way going forward all you need to do is change your object, and the entire set will be changed in the page. 这样一来,您所需要做的就是更改对象,整个页面将被更改。
If not found, use a dummy object: 如果找不到,请使用虚拟对象:
(document.getElementById("ey") || {innerHTML:''}).innerHTML = 'AY'
(document.getElementById("ny") || {innerHTML:''}).innerHTML = 'BY'
(document.getElementById("gy") || {innerHTML:''}).innerHTML = 'CY'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.