我有以下在循环内发生的脚本。我该如何做到这一点,这样我只需将其放置在页面底部一次,而不需要对类进行硬编码?该脚本针对每个 <li>
出现。这看起来很笨重。
这是脚本
<script>
$(".<?php echo strtolower(get_field('code'));?>_btn").click(function(){
$("#<?php echo strtolower(get_field('code'));?>").on('show', function () {
$('iframe.fohl-mobile').attr("src","http://www.psfk.com/home#<?php echo get_field('code');?>");
});
});
</script>
这是循环中重复的整个片段
<li>
<a data-toggle="modal" role="button" class="<?php echo strtolower(get_field('code'));?>_btn" href="#<?php echo strtolower(get_field('code'));?>"> </a>
<img class="lazy" alt="<?php the_title();?>" src="<?php echo site_url('wp-content/fohl/holder.png');?>" data-original="<?php echo site_url('/wp-content/fohl/products/').strtolower(get_field('code'));?>.png" />
<noscript><img src="<?php echo site_url('/wp-content/fohl/products/').strtolower(get_field('code'));?>.png” alt="<?php the_title();?>"/></noscript>
<div class="title"><?php the_title();?>
<div id="<?php echo strtolower(get_field('code'));?>" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<iframe class="fohl-mobile" height="500" width="330" frameborder="0" src=""></iframe>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
<script>
$(".<?php echo strtolower(get_field('code'));?>_btn").click(function(){
$("#<?php echo strtolower(get_field('code'));?>").on('show', function () {
$('iframe.fohl-mobile').attr("src","<?php echo site_url('/home#'.get_field('code'));?>");
});
});
</script>
</li>
最佳答案
也许这对你有用?它未经测试,但从概念上来说似乎没问题。我会测试,但你没有发布 JSFiddle。基本上,您的主触发器可以是一个通用类,而不是循环每次迭代的不同类,它引用其父级来获取更具体的内部内容。
HTML
<a data-toggle="modal" role="button" class="class_for_any_btn" href="#<?php echo strtolower(get_field('code'));?>"> </a>
JS
<script>
$(".class_for_any_btn").click(function(){
$(this).parent().on('show',"#<?php echo strtolower(get_field('code'));?>", function () {
$('iframe.fohl-mobile').attr("src","<?php echo site_url('/home#'.get_field('code'));?>");
});
});
</script>
关于javascript - 不必每次循环都重复脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17711250/