【问题标题】:getting data attrib value from html to jquery从html获取数据属性值到jquery
【发布时间】:2023-03-22 10:39:01
【问题描述】:

所以我有一堆图像,我正在为其添加一些数据属性,我想稍后在 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 大师可以帮助向我展示如何将这个值传递给这个函数。

非常感谢任何帮助!

【问题讨论】:

    标签: javascript php jquery jquery-selectors this


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答。基本上我猜我出错的地方是使用this.data() 而不是$(this).data()
    猜你喜欢
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2014-06-28
    相关资源
    最近更新 更多