3 回答
TA贡献1934条经验 获得超2个赞
var imageid = $('.patient-image').data().uniqueid;
应该
var imageid = $(this).parent().siblings('.patient-image').data().uniqueid;
TA贡献1815条经验 获得超6个赞
以下内容未经测试,但我希望会有所帮助。不需要像您尝试那样使用 ID 来定位元素 - 只需将兄弟选择器和父选择器与querySelector/结合使用即可querySelectorAll。我相信 jQuery 有它自己的方法,但我不能建议它们是什么。
这里的想法是您获得对用于旋转图像的所有按钮的引用,并为每个按钮分配一个通用事件处理程序。调用时的事件处理程序会清除任何先前分配的rotated类并将此 css 类分配给按钮的兄弟图像。
{% for key, file in image_files %}
<div class='image-box'>
<img class='patient-image' src='/{{ src_path }}{{ file }}'>
<p>
<a class='rotate-btn btn'>Rotate</a>
</p>
</div>
{% endfor %}
经过测试的版本
for( $i=0; $i < 10; $i++ ){
echo "
<div class='image-box'>
<img class='patient-image' src='/images/homer_2.png'>
<p>
<a href='#' class='rotate-btn btn'>Rotate</a>
</p>
</div>";
}
<style>
.image-box{clear:none; display:inline-block; margin:1rem; float:left;}
.rotate-btn{padding:1rem;border:1px solid black;background:whitesmoke;cursor:pointer}
img{ transform:rotate(0deg); transition: all 250ms ease-in-out; }
.rotated{ transform:rotate(90deg) }
</style>
<script>
Array.prototype.slice.call( document.querySelectorAll( 'a.rotate-btn' ) ).forEach( bttn=>{
bttn.addEventListener('click', function(e){
e.preventDefault();
/* if other \"rotated\" images are to revert to their original orientation, else remove this or comment it out */
Array.prototype.slice.call( document.querySelectorAll('img.rotated') ).forEach( img=>{img.classList.remove('rotated') })
/* apply the css class to perform the rotation */
let img=this.parentNode.parentNode.querySelector('img');
img.classList.add( 'rotated' );
});
});
</script>
TA贡献1815条经验 获得超13个赞
问题是使用$('.patient-image') 没有上下文的 jQuery 函数,您将检索所有具有该类的元素patient-image。当您应用.data()到元素的选择时,它将用于第一个。这就是为什么该值仅在第一次正确的原因。
我认为你想要的是最接近点击按钮的元素。
var imageid = $(this).closest('.patient-image').data().uniqueid;
因此是我的建议。如果您仅使用“id”和“uniqueid”来标识相应的元素,则使用这种方法应该会过时。
我还建议使用$(...).data('uniqueid')而不是每次都获取所有数据。
要旋转相应的图像,请使用以下代码段:
$( '.rotate-btn' ).on('click', function() {
$(this)
.closest('.patient-image')
.css('transform', 'rotate(90deg)')
});
- 3 回答
- 0 关注
- 207 浏览
添加回答
举报