简体   繁体   English

如何在没有保护条款的情况下重写 jQuery?

[英]How can I rewrite jQuery without guard clause?

How can I rewrite this jQuery to be more terse and without the guard clause?我怎样才能重写这个 jQuery 更简洁并且没有保护条款?

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.如果 jQuery object 的长度为0$('#myTextBox').val("")将什么也不做,所以只需使用它。

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.如果没有选择,则不会枚举任何内容,因此 jQuery 将不会运行val()例程。

It'll work just as $('#myTextBox').val("");它就像$('#myTextBox').val(""); , if it finds no object then it will just be an empty jQuery object and the .val() routine will do nothing. ,如果它没有找到 object 那么它将只是一个空的 jQuery object 并且.val()例程将什么也不做。

I believe that if #mytextbox doesn't exist, mytextbox will not be undefined anyway, it will be an empty jQuery object.我相信如果#mytextbox不存在, mytextbox无论如何都不会未定义,它将是一个空的 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.我还认为,如果您对空的 jQuery object 执行操作,无论如何都不会发生任何事情,所以您很安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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