OnClick可以做两件事吗?

时间:2018-12-01 09:31:31

标签: javascript php wordpress

这是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开头

类似...

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

有可能吗?

2 个答案:

答案 0 :(得分:1)

最好的方法是使用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>标签内的最后一个元素,以便脚本不会中断页面​​的加载。

答案 1 :(得分:-1)

您可以尝试引导模式

example

OR

window.open('http://google.com');
相关问题