从 $(this) 选择器的数组中获取属性
Get attribute from array of $(this) selector
我有一个 jquery 插件,可以使用 ajax 和 php 上传所选照片。
它工作正常,但我需要将所选照片的属性传递给 php。我在 $(this)[0]
中收到 html 元素。我需要这样的东西:
$(this)[0].attr("data-index");
从 $(this)[0]
获取 attr
的正确方法是什么
你必须select像
这样的元素
$($(this))
然后就可以找到属性了
所以你的代码应该看起来像
$($(this)[0]).attr("data-index");
在jQuery中,您可以这样做:
$(this).data("index");
这将使用 jQuery 的 .data()
功能自动访问 data-index
属性。
或者你可以用这个直接读取属性:
$(this).attr("data-index");
因为您知道 jQuery 对象中只有一个元素,所以没有理由使用 [0]
复杂化。虽然你在这里不需要它,但如果你想要 jQuery 对象中的第一个项目并且你想要 jQuery 对象中的结果,你可以使用 .eq(0)
作为 $(this).eq(0).attr("data-index");
,但因为您已经知道 $(this)
中只有一个元素,所以这里没有理由。
或者,在普通 JS 中,您可以这样做:
this.getAttribute("data-index");
或者,在现代浏览器中,您可以这样做:
this.dataset.index
使用较新的.dataset
feature。
我有一个 jquery 插件,可以使用 ajax 和 php 上传所选照片。
它工作正常,但我需要将所选照片的属性传递给 php。我在 $(this)[0]
中收到 html 元素。我需要这样的东西:
$(this)[0].attr("data-index");
从 $(this)[0]
attr
的正确方法是什么
你必须select像
这样的元素$($(this))
然后就可以找到属性了
所以你的代码应该看起来像
$($(this)[0]).attr("data-index");
在jQuery中,您可以这样做:
$(this).data("index");
这将使用 jQuery 的 .data()
功能自动访问 data-index
属性。
或者你可以用这个直接读取属性:
$(this).attr("data-index");
因为您知道 jQuery 对象中只有一个元素,所以没有理由使用 [0]
复杂化。虽然你在这里不需要它,但如果你想要 jQuery 对象中的第一个项目并且你想要 jQuery 对象中的结果,你可以使用 .eq(0)
作为 $(this).eq(0).attr("data-index");
,但因为您已经知道 $(this)
中只有一个元素,所以这里没有理由。
或者,在普通 JS 中,您可以这样做:
this.getAttribute("data-index");
或者,在现代浏览器中,您可以这样做:
this.dataset.index
使用较新的.dataset
feature。