最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - checking to see if data attribute has a value or not - Stack Overflow

programmeradmin4浏览0评论

i am quite new to jquery. i am trying to check on page load if data attribute has a value or is that empty. here is my html

data-tablet="img/xl.jpg"

How i wanna check if there is a path set or is it empty. here is my js

if ($('#myImg').data('tablet')=null) {
alert('Path not Set');
};

But it's giving me an error. can you please tell me how to resolve it. thanks.

i am quite new to jquery. i am trying to check on page load if data attribute has a value or is that empty. here is my html

data-tablet="img/xl.jpg"

How i wanna check if there is a path set or is it empty. here is my js

if ($('#myImg').data('tablet')=null) {
alert('Path not Set');
};

But it's giving me an error. can you please tell me how to resolve it. thanks.

Share Improve this question asked Nov 24, 2014 at 13:43 Cloudboy22Cloudboy22 1,5145 gold badges22 silver badges41 bronze badges 3
  • 7 = is assignment, == is equality and === is identity – blgt Commented Nov 24, 2014 at 13:45
  • 1 As @blgt says, it's likely to be an issue with your syntax. It would be useful if you specify in your question what error you're actually seeing however. – James Thorpe Commented Nov 24, 2014 at 13:45
  • possible duplicate of Can't make multiple if conditions in JavaScript? – Qantas 94 Heavy Commented Nov 24, 2014 at 14:08
Add a ment  | 

3 Answers 3

Reset to default 9

First as pointed out in ments, you are missing an equal sign so you are not doing a parison. Second issue is that if there is no data attribute it is undefined, not null.

if ($('#myImg').data('tablet')===undefined) {

You could use this.

if (!$('#myImg').data('tablet')) {
  alert('Path not Set');
};

In Javascript every object is convertible to a boolean, so if it's null or an empty string it'll be false, otherwise it'll be true.

You can check whether data attribute have data or exist by using the following code in jquery.

In the beginning, there was typeof. This handy operator gives you the "type" of a javascript value

if(typeof $('#myImg').data('tablet') != 'undefined') {
  // data exist
} else {
  // data not exist or undefined
}
发布评论

评论列表(0)

  1. 暂无评论