1 回答
TA贡献1812条经验 获得超5个赞
下面应该向您展示如何定位元素,但是根据您想要实现的目标,您可能需要绑定到一个事件作为起点并显然采取进一步的行动......
使用 jQuery ...
var parentElem = jQuery('.add_to_cart_form .btn-primary').closest('.product-teaser__bottom');
var data = jQuery('.price-without-discount', parentElem).text();
console.log(data);
(function($){
var btn = $('.add_to_cart_form .btn-primary');
btn.on('click', function(e){
e.preventDefault();
var parentElem = $(this).closest('.product-teaser__bottom');
var data = $('.price-without-discount', parentElem).text();
console.log(data);
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="product-teaser__bottom">
<div class="product-teaser__price-block">
<div class="product-teaser__price-without-discount"></div>
<div class="product-teaser__price">
<span class="price-without-discount">437,00</span>
<span class="product-teaser__price-currency">CZK</span>
</div>
</div>
<div class="product-teaser__add-to-cart">
<form class="add_to_cart_form">
<button class="btn btn-primary">Test Button</button>
</form>
</div>
</div>
使用香草javascript ...
/**
* Element.closest Polyfill
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
*/
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
}
if (!Element.prototype.closest) {
Element.prototype.closest = function(s) {
var el = this;
do {
if (Element.prototype.matches.call(el, s)) return el;
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
};
}
var btnElem = document.querySelector('.add_to_cart_form .btn-primary');
var parentElem = btnElem.closest('.product-teaser__bottom');
var data = parentElem.querySelector('.price-without-discount').textContent;
console.log(data);
btnElem.addEventListener('click', function(e){
e.preventDefault();
var parentElem = this.closest('.product-teaser__bottom');
var data = parentElem.querySelector('.price-without-discount').textContent;
console.log(data);
}, false);
<div class="product-teaser__bottom">
<div class="product-teaser__price-block">
<div class="product-teaser__price-without-discount"></div>
<div class="product-teaser__price">
<span class="price-without-discount">437,00</span>
<span class="product-teaser__price-currency">CZK</span>
</div>
</div>
<div class="product-teaser__add-to-cart">
<form class="add_to_cart_form">
<button stype="submit" class="btn btn-primary">Test Button</button>
</form>
</div>
</div>
添加回答
举报