【发布时间】:2019-07-01 09:48:19
【问题描述】:
我有一个下拉切换器来更改商店视图。单击下拉列表中的选项后,我想实现一个用 PHP 完成的函数。
我一直在尝试通过 Jquery 实现此事件,如下所示:
<?php if (count($block->getGroups()) > 1): ?>
<div class="switcher store switcher-store" id="switcher-store">
<strong class="label switcher-label"><span><?php /* @escapeNotVerified */
echo __('Select Store') ?></span></strong>
<div class="actions dropdown options switcher-options">
<?php foreach ($block->getGroups() as $_group): ?>
<?php if ($_group->getId() == $block->getCurrentGroupId()): ?>
<div class="action toggle switcher-trigger"
role="button"
tabindex="0"
data-mage-init='{"dropdown":{}}'
data-toggle="dropdown"
data-trigger-keypress-button="true"
id="switcher-store-trigger">
<strong>
<span><?php echo $block->escapeHtml($_group->getName()) ?></span>
</strong>
</div>
<?php endif; ?>
<?php endforeach; ?>
<ul class="dropdown switcher-dropdown" data-target="dropdown">
<?php foreach ($block->getGroups() as $_group): ?>
<?php if (!($_group->getId() == $block->getCurrentGroupId())): ?>
<li class="switcher-option">
<a href="#" data-post='<?= $block->getTargetStorePostData($_group->getDefaultStore()); ?>'>
<?php echo $block->escapeHtml($_group->getName()) ?>
</a>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</div>
</div>
<?php endif; ?>
<script>
require(['jquery', 'jquery/ui'], function($){
$("#switcher-option").trigger("click", clickConfirm());
function clickConfirm(){
var isGood=confirm('You will lose your cart items if you switch between seasons!');
if (isGood) {
<?php $seasonsHelper->getClearCart(); ?>
} else {
<?php $this->getUrl('*');?>
}
}
});
</script>
商店更改完美运行,但确认事件出现在不同的地方,不仅在我选择下拉按钮时。如果我添加到购物车,它也会出现,当我加载页面时,它也会出现。
我一直在尝试使用“.class”或“#id”来准确识别标识符,但没有任何效果。
这是正确的做法吗?
【问题讨论】:
-
这里没有任何 ID 为
switcher-option的元素,因此$("#switcher-option")不会选择任何开头的元素。而在这个地方触发一个事件可能也不是你想在这里做的。这可能应该类似于$(".switcher-option").on("click",function() { … });。 -
您好,请从单击事件中的 clickConfirm 中删除括号:
$("#switcher-option").on("click", clickConfirm);。如果您留下括号,该函数将在加载时自动执行。也使用oninsted oftrigger因为trigger将启动一个事件而不是监听它
标签: php jquery click magento2 magento2.2