javascript - OnClick 可以做两件事吗?
问题描述
这是html代码...
<div id="video-embeds">
<div id="Div1">
<input id="Button1" type="button" value="►" 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() ) ); ?>
是否可以?
解决方案
最好的方法是使用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>
,这样脚本就不会中断页面的加载。
推荐阅读
- haskell - Haskell:理解 Applicative 函子的纯函数
- c++ - (type)(math expression) 是否将表达式计算为这种类型?
- python - 在“if/elif/else”语句中调用了不正确的代码
- node.js - 如何阻止来自外部的随机呼叫
- xslt-2.0 - XSLT on XML 从混合节点获取父值
- swift - 致命错误:没有足够的位来表示传递的值
- r - Rcpp 对象似乎被 R 的垃圾收集器销毁
- linux - 为什么我编译的 C++ 二进制文件不能执行?
- php - 选中/未选中复选框值时更新数据透视表
- python - 如何修复“ImportError:无法导入名称'StringIO'”