首页 > 解决方案 > OnClick 可以做两件事吗?

问题描述

这是html代码...

<div id="video-embeds">
<div id="Div1">
<input id="Button1" type="button" value="&#9658;" onclick="switchVisible();"  style="font-size: 40px; font-weight: bold; line-height: 2; background-color: #000; text-align: center; color: #fff; margin-bottom: 0px; z-index: 102; background: url('.get_post_meta(get_the_ID(), 'fifu_image_url', TRUE).') no-repeat; background-size: cover; position: relative; padding-bottom: 56.25%; padding-top: 0px; height: 0; margin-bottom: 0px; width: 100%; font-size: 120px; line-height: 5;"/>

    </div>
    <div id="Div2" class="video-embed" style="font-size: 40px; font-weight: bold; line-height: 2; background-color: #000; text-align: center; color: #fff; margin-bottom: 0px; z-index: 102;display:none;">'.
    do_shortcode('[video_display]').'
    </div>
    </div>

这是剧本...

<script type="text/javascript">
function switchVisible() {
            if (document.getElementById('Div1')) {

                if (document.getElementById('Div1').style.display == 'none') {
                    document.getElementById('Div1').style.display = 'block';
                    document.getElementById('Div2').style.display = 'none';
                }
                else {
                    document.getElementById('Div1').style.display = 'none';
                    document.getElementById('Div2').style.display = 'block';
                }
            }
}
</script>

我想在新的弹出窗口或新窗口中添加 url 打开也 onclick 输入为

就像是...

https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode( get_permalink( get_the_ID() ) ); ?>

是否可以?

标签: javascriptphpwordpress

解决方案


最好的方法是使用addEventListener,而完全忘记该onclick属性。删除代码onclick中的<button>并将其添加到脚本中:

document.getElementById("Button1").addEventListener("click", (e) => {
   /* write code for stuff button is supposed to do when clicked */
});

这样,您就可以将 JavaScript 与 HTML 分开,从而生成更好的代码。您可以按名称调用函数,而不是调用匿名函数(e) => { ... }function() { ... },如果您希望在单击按钮时运行多个函数,则可以重复执行此操作:

document.getElementById("Button1").addEventListener("click", functionName1);
document.getElementById("Button1").addEventListener("click", functionName2);
/* etc... */ 

使用该代码,当单击按钮时,两者都将运行functionName1()functionName2()

更多信息:https ://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

并确保<script>标签是标签内的最后一个元素<body>,这样脚本就不会中断页面​​的加载。


推荐阅读