获取未定义的值 jQuery 和 Html

我有这个HTML代码:


<div class="cart-plus-minus">

  <input class="cart-plus-minus-box quantity" id="{{ $item->id }}" name="quantity[{{ $i }}]" value="{{ $item->quantity }}" type="text">

  <input  name="product_id[{{ $i }}]" value="{{ $item->id }}" type="hidden">

  <div class="dec qtybutton" data-attribute="{{ $item->id }}"><i class="zmdi zmdi-chevron-down"></i></div>

  <div class="inc qtybutton" data-id="{{ $item->id }}"><i class="zmdi zmdi-chevron-up"></i></div>

</div>

我的jQuery代码是这样的:


$(document).on('click', 'div.cart-plus-minus > div.dec', function (event) {

    var element = jQuery(event.currentTarget);

    var url = element.attr("attribute");

    alert(url);

});

当我点击desc时,它会显示一个警报,但问题是值是未定义的,我知道这是因为它说$(文档),但这是它工作的唯一方式......我想知道如何获取数据属性中的值?


holdtom
浏览 87回答 3
3回答

ITMISS

获取数据使用或.data("foo").attr("data-foo")$(document).on('click', 'div.cart-plus-minus > div.dec', function (event) {&nbsp; &nbsp; var url = $(this).data("attribute");&nbsp; &nbsp; alert(url);});例:$(document).on('click', 'div.cart-plus-minus > div.dec', function(event) {&nbsp; var url = $(this).data("attribute"); // That's not an URL but OK&nbsp; alert(url);});<div class="cart-plus-minus">&nbsp; <input class="cart-plus-minus-box quantity" id="888" name="quantity[0]" value="0" type="text">&nbsp; <input name="product_id[0]" value="888" type="hidden">&nbsp; <div class="dec qtybutton" data-attribute="888"><i class="zmdi zmdi-chevron-down"> DEC</i></div>&nbsp; <div class="inc qtybutton" data-id="888"><i class="zmdi zmdi-chevron-up"> INC</i> </div></div><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>给定链接中的示例,您有如下内容:$(".dec, .inc").on('click', function() {&nbsp; const $inp = $(this).closest('.cart-plus-minus').find('.cart-plus-minus-box');&nbsp; let val = Number($inp.val());&nbsp; val += $(this).is('.inc') ? 1 : -1;&nbsp;&nbsp; $inp.val(Math.max(0, val));});<div class="cart-plus-minus">&nbsp; <input class="cart-plus-minus-box" name="quantity" value="1" type="text">&nbsp; <button type="button" class="dec qtybutton"><i class="zmdi zmdi-chevron-down">-</i></button>&nbsp; <button type="button" class="inc qtybutton"><i class="zmdi zmdi-chevron-up">+</i></button></div><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>此外,修复模板问题。

芜湖不芜

你可以做这样的事情:$(document).on('click', 'div.cart-plus-minus > div.dec', function (event) {&nbsp; &nbsp; alert($(this).data('attribute'));});

犯罪嫌疑人X

使用 data() 而不是 attr:element.data("attribute");
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript