如何根据另一个元数据中的事件点击获取一个元数据中的值?
<button type="button"
class="btn btn btn-danger"
data-action="voltar-tela-pedidos"
data-scroll-to="pedido-00C407948 ">
</button>
jQuery(document).on("click", '[data-action="voltar-tela-pedidos"]', function (e) {
// i want to know the value of data-scroll-to
});
最佳答案
jQuery(document).on("click", '[data-action="voltar-tela-pedidos"]', function(e) {
var myScrollTo = jQuery(this).data('scroll-to');
// or
var myScrollTo = jQuery(this).attr('data-scroll-to');
});
检查 demo fiddle here .
jQuery(document).on("click", '[data-action="voltar-tela-pedidos"]', function(e) {
var myScrollTo1 = jQuery(this).data('scroll-to');
// or
var myScrollTo2 = jQuery(this).attr('data-scroll-to');
console.log(myScrollTo1, myScrollTo2)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn btn-danger" data-action="voltar-tela-pedidos" data-scroll-to="pedido-00C407948 ">CLICK ME</button>
$(...).data
不是函数
When I use this, I receive the error:
$(...).data is not a function
当您将 jQuery 添加到您的页面时,它 "registers itself"在全局变量 $
和 jQuery
中。
但是这些变量可以被覆盖。
可能,在您的网页上下文中,$
不是 jQuery,而是其他一些 lib*。在这种情况下,始终使用 jQuery(...)
而不是 $(...)
。
* Prototype还使用全局变量 $
,这可能是覆盖 jQuery 的内容。我还看到一些基于 RichFaces/JSF 的应用程序使用 $
全局变量。
如何判断$
是不是jQuery?
只需在您的控制台中输入:
console.log($)
console.log($.fn.jquery)
如果你的 $
是 jQuery,它应该输出类似的东西(第二行是加载的 jQuery 版本):
// this is what stackoverflow.com prints for those commands right now. try it out.
ƒ (a,b){return new n.fn.init(a,b)}
1.12.4
较旧的 jQuery 版本略有变化,但第二个命令 (console.log($.fn.jquery)
) 始终打印版本。
如果您在执行这些命令时遇到错误,您的 $
可能是其他一些库。在这种情况下,通过检查您的 jQuery
变量确认至少加载了 jQuery:
console.log(jQuery)
console.log(jQuery.fn.jquery)
输出应该类似于上面显示的示例。
关于javascript - 从jQuery中的点击获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45845073/