【问题标题】:Error while accessing data attributes in console.log访问 console.log 中的数据属性时出错
【发布时间】:2015-02-27 08:46:31
【问题描述】:

我正在尝试访问 js 中的数据属性。但显示error="Uncaught type error"

var x=document.getElementById(this.id);
console.log(x.src);
console.log(x.data('image'));

对于 x.src 我越来越完美-“http://localhost:3000/uploads/asset/asset3/199/small_ring3.jpg”,但是当我尝试 x.data('image') 时,它显示-“未捕获的 TypeError: undefined is not a function58:646 (anonymous function) jquery.min.js:3 m.event.dispatchjquery.min.js:3 m.event.add.r.handle"

这里x是

img alt="Small ring3" class="img-thumbnail" data-image="/uploads/asset/asset3/199/large_ring3.jpg" id="2" src="http://localhost:3000 /uploads/asset/asset1/199/large_ring1.jpg"

请帮忙。

【问题讨论】:

  • 第二个 console.log() 调用结束时缺少括号')'
  • 据我所知,x 不是 jquery 对象,试试 var x = $('#'+this.id);
  • console.log(x.data('image'));抱歉,这里是拼写错误,不在我的代码中。它显示“Uncaught TypeError: undefined is not a function”

标签: javascript


【解决方案1】:

使用getAttribute()

console.log( x.getAttribute('data-image') );

【讨论】:

  • 这是正确的纯JS解决方案,可以去掉问题中的jquery标签。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 2020-09-25
  • 2021-05-21
相关资源
最近更新 更多