[英]Javascript Try Catch for DIV
I am trying to build a catch try to execute some javascript code. 我正在尝试构建一个catch尝试执行一些JavaScript代码。 NO JQUERY I want to identify if a div id ('test') exists and if it doesn't don't execute the code.
NO JQUERY我想识别div id('test')是否存在以及它是否不执行代码。 How would I do this?
我该怎么做? I know the structure of a try catch is
我知道try catch的结构是
try{
}
catch(e){
}
use try-catch
as less as possible: just check whether or not the DOM element exists: 尽可能少地使用
try-catch
:只检查DOM元素是否存在:
if (document.getElementById('test')!=null) {
// element (div) with id 'test' exists
}
else {
// it doesn't
}
I would make things simpler and use if
instead of try-catch
. if
不是try-catch
我会使事情更简单并使用。 try-catch
is designed for exceptional situations, when you really don't know what to do throw an error. try-catch
是针对特殊情况而设计的,当你真的不知道该怎么做时会抛出一个错误。 Throwing an error causes the whole code block to terminate it's execution. 抛出错误会导致整个代码块终止它的执行。
I would do like this: 我想这样做:
var divId = 'test';
if (document.getElementById(divId)) {
alert('exists');
} else {
alert('does not exist');
}
There is no need to check document.getElementById()
result on null
(in all modern browsers null
is returned when no element is found). 无需在
null
上检查document.getElementById()
结果(在所有现代浏览器中,如果未找到任何元素,则返回null
)。 In most JavaScript projects developers skip typing !== null
since null
is treated as false
and DOM object is treated as true
, so programmers avoid typing obvious things. 在大多数JavaScript项目中,开发人员都会跳过输入
!== null
因为null
被视为false
而DOM对象被视为true
,所以程序员避免输入明显的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.