如何通过jquery按钮获得特定值?
我正在使用EJS来实现前端。这是图库,我想在用户点击按钮时获得图像的某些文件名。我在下面展示了我的代码
<% if(files || files == null) { %>
<% files.forEach(function(file) { %>
<% if(file.isImage){ %>
<!-- Single Product -->
<div class="col-12 col-sm-6 col-lg-4"
id="single_product">
<div class="single-product-wrapper">
<!-- Product Image -->
<div class="product-img">
<a href="/<%=file.filename %>">
<img src="image/<%=file.filename %>"
alt=""></a>
<div class="add-to-cart-btn">
<button type="button" id="addToCart"class="btn essence-btn"
>Add to Cart</button>
</div>
<% } else { %>
<p>ERROR</p>
<% } }) } else {%>
<p>No files</p>
<% } %>
JQUERY FILE
<script type="text/javascript">
$(document).ready(function(){
$('#addToCart').click(function(){
});
});
</script>
我不知道如何实现这一点。有小费吗
回答如下:看起来你的addToCart
按钮有一个ID并且在for
循环内 - 所以这不好。 ID是唯一的 - 使用类,然后使用this
的实例来获取正确的src
属性:
更新HTML代码段:
<button type="button" class="btn essence-btn js-btn-add-to-cart">Add to Cart</button>
更新了JS:
$(document).ready(function(){
$('.js-btn-add-to-cart').click(function(){
var clickedImageSrc = $(this).closest(".single-product-wrapper").find("img").attr("src");
});
});
如何通过jquery按钮获得特定值?
我正在使用EJS来实现前端。这是图库,我想在用户点击按钮时获得图像的某些文件名。我在下面展示了我的代码
<% if(files || files == null) { %>
<% files.forEach(function(file) { %>
<% if(file.isImage){ %>
<!-- Single Product -->
<div class="col-12 col-sm-6 col-lg-4"
id="single_product">
<div class="single-product-wrapper">
<!-- Product Image -->
<div class="product-img">
<a href="/<%=file.filename %>">
<img src="image/<%=file.filename %>"
alt=""></a>
<div class="add-to-cart-btn">
<button type="button" id="addToCart"class="btn essence-btn"
>Add to Cart</button>
</div>
<% } else { %>
<p>ERROR</p>
<% } }) } else {%>
<p>No files</p>
<% } %>
JQUERY FILE
<script type="text/javascript">
$(document).ready(function(){
$('#addToCart').click(function(){
});
});
</script>
我不知道如何实现这一点。有小费吗
回答如下:看起来你的addToCart
按钮有一个ID并且在for
循环内 - 所以这不好。 ID是唯一的 - 使用类,然后使用this
的实例来获取正确的src
属性:
更新HTML代码段:
<button type="button" class="btn essence-btn js-btn-add-to-cart">Add to Cart</button>
更新了JS:
$(document).ready(function(){
$('.js-btn-add-to-cart').click(function(){
var clickedImageSrc = $(this).closest(".single-product-wrapper").find("img").attr("src");
});
});