How can I rewrite jQuery without guard clause?
How can I rewrite this jQuery to be more terse and without the guard clause?
var myTextBox = $('#myTextBox');
if (myTextB开发者_运维技巧ox )
myTextBox.val("");
The guard clause is there simply to ensure that the element exists on the page before trying to set it's value but the code seems bloated and most of it unnecessary. What's the preferred solution to this?
$('#myTextBox').val("")
will do nothing if the jQuery object has a length of 0
, so simply use it.
Unless you need to cache the selector for future operations, I would do this:
$('#myTextBox').val("")
If there are none selected, nothing will get enumerated, so jQuery will not run the val()
routine.
It'll work just as $('#myTextBox').val("");
, if it finds no object then it will just be an empty jQuery object and the .val()
routine will do nothing.
I believe that if #mytextbox
doesn't exist, mytextbox
will not be undefined anyway, it will be an empty jQuery object. So the check is redundant.
I also think that if you perform an operation on an empty jQuery object nothing will happen anyway, so you're safe.
精彩评论