图像& img src 的ID由Jinja2模板&动态生成。图像通过函数返回。 因此,我希望在按钮元素上使用 $ this jquery选项来获取 img src。 这是jinja2模板代码......
<div id="center-container" class="span9">
{% for article_row in images | batch(3, ' ') %}
<ul class="thumbnails">
{% for article in article_row %}
<li class="span3">
<div class="thumbnail">
<img src ="img/{{ article|e }}" data-src="holder.js/360x270" alt="" id="img{{loop.index}}">
<h3>Thumbnail label</h3>
<p>{{ article }}</p>
</div>
<button class="btn btn-inverse" type="button" id="img{{loop.index}}">Large button</button>
</li>
{% endfor %}
</ul>
{% endfor %}
</div>
这是渲染后的页面src:
<html>
<head>
</head>
<body>
<div id="center-container" class="span9">
<ul class="thumbnails">
<li class="span3">
<div class="thumbnail">
<img src ="img/allofthethings.png" data-src="holder.js/360x270" alt="" id="img1">
<h3>Thumbnail label</h3>
<p>allofthethings.png</p>
</div>
<button class="btn btn-inverse" type="button" id="img1">Large button</button>
</li>
<li class="span3">
<div class="thumbnail">
<img src ="img/brogrammer.jpg" data-src="holder.js/360x270" alt="" id="img2">
<h3>Thumbnail label</h3>
<p>brogrammer.jpg</p>
</div>
<button class="btn btn-inverse" type="button" id="img2">Large button</button>
</li>
<li class="span3">
<div class="thumbnail">
<img src ="img/couragewolf.jpg" data-src="holder.js/360x270" alt="" id="img3">
<h3>Thumbnail label</h3>
<p>couragewolf.jpg</p>
</div>
<button class="btn btn-inverse" type="button" id="img3">Large button</button>
</li>
</ul>
</div>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="../inc/js/bootstrap.min.js"></script>
</body>
这是我收到错误的地方: js功能
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function(){
var src=$(this).attr("src");
alert(src);
alert($(this).attr('src'));
console.log(src);
});
});
</script>
答案 0 :(得分:1)
ID必须是唯一的,您似乎对按钮和img元素具有相同的ID
,$(this)
指的是button
,而按钮没有src
属性,所以改变:
var src=$(this).attr("src");
到
var src=$(this).parents("li.span3").find("img").attr("src");
答案 1 :(得分:1)
没有'src'属性。试试这段代码:
$(document).ready(function() {
$("button").click(function(){
var src=$(this).parent().find('img').attr('src');
console.log(src);
});
});
答案 2 :(得分:0)