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
精彩评论