简体   繁体   English

有没有更好的方法在jquery中执行此操作?

[英]Is there any better way to do this in jquery?

I want to know that is there any better method to do : 我想知道有没有更好的方法:

var name = $('input').attr("name") != "undefined" ? $('input').attr("name") : "";

Here i am reading the name attribute of input . 这里我正在阅读inputname属性。 My problem is when i read the name for newly created text element, then it was undefined . 我的问题是当我读取新创建的text元素的name时,它是undefined So for not showing undefined to the user i have to put this check.Now i have to ready so many properties and in all of then the same problem exist so that`s why i want to know that, Is there any better way to deal will this? 因此,为了不向用户显示undefined ,我必须把这个检查。现在我必须准备这么多属性,然后存在同样的问题所以这就是为什么我想知道,有没有更好的方法来处理这会吗?

You don't have to explicitly compare it to undefined. 您不必明确地将其与undefined进行比较。 undefined will return false when used in an if statement. 当在if语句中使用时,undefined将返回false。 By using OR operation you can assign empty string in that case. 通过使用OR操作,您可以在这种情况下分配空字符串。

var name = $('input').attr("name") || '';

Also undefined and "undefined" are not equal in JavaScript. 在JavaScript中,未定义和"undefined"也不相同。 Your original code would already get false negatives. 您的原始代码已经得到假阴性。

短路评估:(我喜欢JS)

var name = $('input').attr("name") || '';

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

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