所以我有一堆图像,我要为其添加一些数据属性,稍后我想在 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 大师可以帮助我展示如何将该值传递到这个函数中。
非常感谢任何帮助!
最佳答案
我将使用each
循环,获取属性,然后调用cropper
$(".img-holder > img").each(function() {
var size = $(this).data("aspect-ratio");
$(this).cropper({
aspectRatio: size
});
});
关于javascript - 从html获取数据属性值到jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27533737/