简体   繁体   中英

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 (myTextBox )
    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM