2017-10-19 25 views
2

当我使用jQuery时,我总是怀疑一个特定的函数是否可以安全运行。例如:jQuery总是安全地运行函数吗?

$('#myButton').removeClass('hello'); // will this break if the 'hello' class isn't present? 

$('#myButton').addClass('hello'); // will this duplicate the 'hello' class if it already exists on the button? 

$('#myButton').text('newText'); // will this run to completion if the text on the element already says 'newText' 

这些都是一些例子,但我的首要问题涉及到jQuery的是否有其功能的安全性背后的一些理念。假设我们作为开发者应该进行安全检查是否安全?或者我们可以假设jQuery的函数已经建立了安全检查吗?

此外,我特别好奇上面三个例子中的最后一个。它是否像这样运行:

if ($myButton.text() !== 'newText') { 
    $myButton.text('newText'); 
} 

或者干脆像这样:

$myButton.text('newText'); 
+2

简短回答:是的,即使您引用的元素/ class/text/etc不存在,jquery通常不会抛出错误,并且不会出现,addClass不会重复类。它主要是'只是工作' –

+0

你可以自己测试这些很容易,但要回答你的问题,不,它不会中断,不,它会运行完成,jQuery在运行方法时有内置空/空检查jQuery对象,第二个例子很好。 –

回答

1

正如其他人所说,JQuery的那张让开,当你通过它缺少的选择不会打破。至于其他的问题,看看代码:

this.empty().each(function() { 
    if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { 
     this.textContent = value; 
    } 
}); 

看起来它实际运行.empty()来清理元素,然后注入的内容,不管它是相同的内容。