从同一外部容器中的另一个 link 获取 html data-* 属性

Getting html data-* attribute from another link in the same outer container

下面是 HTML 代码,它生成一个部分,其中包含 woocommerce 产品列表中的一个特定产品。我在 fist link 中放置了一个 function directLink() 这样我就可以使用 [=40 将一个人重定向到一个页面=] 来自该部分的 最后 link

通过点击,我什至只能在页面上找到特定的 link,但我无法从中获取 data-product_sku 数据,只能将其解析为字符串,但我'我确定有办法直接用 javascript.

找到它

html:

<li class="post-2028">
  <a href="http:..." class="woocommerce-LoopProduct-link">
    <span onclick="directLink(event); return false;">
      First Link
    </span>
    <div itemprop="description">
    <p>...Product Description...</p>
    </div>
  </a>
  <a href="http:..." data-quantity="1" data-product_id="2028" data-product_sku="323">
    Last Link
  </a>
</li>

js:

function directLink(e) {
    var elmnt = e.path[2].children[1];
}

我明白了

elmnt = '<a href="http:..." data-quantity="1" data-product_id="2028" data-product_sku="323">Last Link</a>'

我也试过了:

var elmnt = e.path[2].children[1];
$(elmnt).data('product_sku');

但这给出了 undefined

如何通过js获取该属性?

您可以执行以下操作:

e.path[2].children[1].dataset.product_sku

会return你期待什么323

您想使用 .attr() 方法。试试像

    $(elmnt).attr('data_product_sku');

或者,这不需要 jQuery。使用纯 JavaScript,这看起来像

    elmnt.getAttribute('data_product_sku');