0

In my markup, my A element has a href equal to "": <a href="">. When trying to display it though using an like for example alert(jQuery('#my_href_link').attr('href')), it returns "undefined" rather than an empty chain or something.

So the solutions I found everywhere:

if (jQuery('#my_href_link').attr('href') == '') 

or

if (jQuery('#my_href_link').attr('href').length == 0)

... don't work.

Yet they seem to work for everybody except me. Why is that?

Markup:

<a id="my_href_link" href="">
    <img src="image.jpg">
</a>
4

1 回答 1

6

Take advantage of the truthy and falsey nature of Javascript variables. In this if statement an empty string or undefined will cause the conditional to evaluate to false.

if (jQuery('#my_href_link').attr('href'))

You can easily negate this statement using ! since the following == true:

alert(!undefined);
alert(!"");

Read more about truthy and falsey

于 2013-10-24T11:56:46.390 回答