javascript - OnClick 可以做两件事吗?

标签 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 opening 也 onclick input as

有点像...

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

这可能吗?

最佳答案

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

关于javascript - OnClick 可以做两件事吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53569445/

相关文章:

javascript - bacon.js 中的控制流,如何在给定时间做某事

javascript - Node.js 是构建完整网站的好选择吗?

javascript - 为什么我的图库中的图像返回 403 错误?

php - PHP 中的元音编码错误

javascript - 如何从提供 NET::ERR_CERT_AUTHORITY_INVALID 的站点获取数据

php - 从 SQL 数据库中检索 varbinary 图像

php - 将 Plesk 的 PHP 版本更改为 PHP 7

php - 仅显示 WordPress 子类别

html - 如何使用 css 定位和设置 Google recaptcha 的样式?

wordpress - 如何在 WordPress 中集成 Razorpay 支付网关