我有一个下拉菜单,用于更改商店视图。单击下拉菜单中的选项后,我想实现一个用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”来准确标识标识符,但没有任何效果。
这是正确的方法吗?
答案 0 :(得分:0)
您需要对JS代码进行一些更改:
require(['jquery', 'jquery/ui'], function($){
if( $("#switcher-option").lengh>0 ){ /// check for element existance
$("#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('*');?>
}
}
});
注意:代码未经测试,只是共享逻辑。