将数据属性值从html获取到jquery

时间:2014-12-17 19:54:00

标签: javascript php jquery jquery-selectors this

所以我有一堆图像,我正在添加一些数据属性,我想稍后在jquery中使用。

PHP / HTML看起来像这样:

<? 
foreach($images as $image) 
{
?>
<div class='dyn-img'>
  <img <!-- start image tag -->
      src="<? echo $image['src']?>"
      data-aspect-ratio ="<? echo $image['aspect_ratio']?>"
      ... //other dynamic data attribs
  > <!-- end image tag -->
</div>
<?
}
?>

稍后在jQuery中,我需要获取这些动态加载的图像并将其宽高比传递到库函数中:

所以在我执行的jQuery部分(在document.ready fn中):

$(".img-holder > img").cropper({
  aspectRatio: 1, //<-- this needs to be the data-aspect-ratio defined earlier
  ... other attributes...
});

我尝试使用aspectRatio: this.data("aspect-ratio")然而这给了我一个javascript错误说

TypeError: this.data is not a function
aspectRatio: this.data("aspect-ratio"),

我的jQuery技能是基本的,所以我希望这里有一些jQuery / Javascript大师可以帮助告诉我如何将该值传递给这个函数。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

我会使用each循环,获取属性,然后调用cropper

$(".img-holder > img").each(function() {
    var size = $(this).data("aspect-ratio");
    $(this).cropper({
        aspectRatio: size
    });
});