开发者

More efficient way to set variable from multiple sources?

开发者 https://www.devze.com 2023-02-07 19:19 出处:网络
I am trying to set a variable in Javascript.I want the variable to use one of the foll开发者_运维问答owing.

I am trying to set a variable in Javascript. I want the variable to use one of the foll开发者_运维问答owing.

1st choice if exists

$(this).attr("data-name");

2nd choice if above doesnt exist

$(this).attr("name");

3rd choice if neither above dont exist

$(this).attr("id");

And when I say doesnt exists I mean not null, not undefined and not blank.

I am not sure an efficient way to do this in javascript could use a bit of help on this.


You can use the || operator:

var name = $(this).data('name') || this.name || this.id;

This says "use the data-name attribute; if it is falsy, use the name property; if it is falsy, use the id property."

Falsy values are:

  • false
  • null
  • undefined
  • an empty string
  • the number 0
  • NaN
0

精彩评论

暂无评论...
验证码 换一张
取 消