javascript - 从html获取数据属性值到jquery

标签 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 大师可以帮助我展示如何将该值传递到这个函数中。

非常感谢任何帮助!

最佳答案

我将使用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/

相关文章:

javascript - jQuery 计算来自服务器的 img 的真实高度/宽度值

php - 使用 PHPMailer 通过 SMTP 发送电子邮件

php - 我正在尝试使用 php 从我的域服务器从 mysql 获取数据到 android 应用程序

jquery - elements breaks xhtml 替代方案是 span 无法在其上添加填充或边距

javascript - 根据下拉框切换添加和删除html

Jquery 查找非父元素

javascript - 控制 flash 在 node-webkit 中打开的窗口

javascript - iron-flex-layout 未应用于主文档

javascript - 当我在正则表达式中包含数组引用时测试失败(正则表达式中带有索引的数组)JavaScript

php - 显示数据库值检索错误