我正在开发一个 WordPress 网站,它(当然)由多个 PHP 模板组成。我遇到问题的特定模板片段是用这一行调用的:
<script id="templatehidden">
<?php get_template_part( 'fragments/calculator', 'row-sa' ); ?>
</script>
calculator-row-sa.php 的内容是:
<div class="form-row pricingrow select-multiple">
<div class="form-controls">
<img class="remove-field-sa" style="float: left; margin-right: 30px;" src="http://45.32.89.214/wp-content/uploads/2016/04/minus.png">
<i style="margin-left: 50px;" class="cardinal"></i>
<select name="field-followers[]" class="select followerselect">
<?php foreach ( $options as $option ) : ?>
<option value="<?php echo $option[ 'value' ] ?>"><?php echo $option[ 'label' ] ?></option>
<?php endforeach; ?>
</select>
<b class="fa fa-caret-down" aria-hidden="true" style="color: #747474";></b>
<span class="acctprice"></span>
</div><!-- /.form-controls -->
而其背后的 jQuery 代码是
$('.remove-field-sa').click(function () {
$(this).closest('.form-row').remove();
});
我的问题是 php.ini 中的 img 元素。当页面首次加载时,它会完成其工作并删除其所在的行。但是,在我添加更多行后,.form-content 中似乎不再执行任何 JavaScript 代码。关于哪里出了问题有什么想法吗?
最佳答案
假设您使用 javascript 添加行,则需要事件委托(delegate):在绑定(bind)事件处理程序时,元素不存在,当您添加它们时,click
事件是除非您使用事件委托(delegate),否则不会自动绑定(bind)到这些新元素。
您可以使用以下示例轻松更改它:
$('.form-content').on('click', '.remove-field-sa', function () {
$(this).closest('.form-row').remove();
});
请注意,此处 .form-content
元素必须出现在页面加载时。如果不是,您也可以使用类似以下内容:
// Any parent element that is present at page-load and will contain the child elements will do.
$('body').on('click', '.remove-field-sa', function () {
$(this).closest('.form-row').remove();
});
关于javascript - 从 PHP 调用的 jQuery 代码不会执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36937860/