JS:如何在onclick里写条件语句

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS:如何在onclick里写条件语句相关的知识,希望对你有一定的参考价值。

<script language="javascript">
function tanchuan()

if(center.style.display=="none")

center.style.display="block"

else

center.style.display="none"


</script>

这段代码在onclick=""里怎么写?
我的html代码是这样的
<div id="top" onclick="">
</div>
<div id="center" style="display:none;">
</div>
我想用上面DIV控制下面DIV的显示和隐藏

需要准备的材料分别有:电脑、html编辑器、浏览器。

1、首先,打开html编辑器,新建html文件,例如:index.html,编写问题基础代码。

2、将index.html的<button>标签中的onclick属性调整为:onclick="tanchuan()"。

3、浏览器运行index.html页面,此时点击btn按钮就会执行tanchuan()函数中的条件语句了。

参考技术A 这段代码全写在onclick里没什么意义吧,可读性低了一些,而且方法的复用性降低了太多。还是用原来的方法写吧,然后修改一下:

<script language="javascript">
function tanchuan()

var bing = document.getElementById("center")

if(bing.style.display=="none")

bing.style.display="block"

else

bing.style.display="none"


</script>

然后再调用onclick时直接就是onclick="tanchuan()"本回答被提问者采纳
参考技术B 一定要卸载onclick里么?直接在前面声明,然后在onclick="tanchuang()"就行了
另外center改成document.getElementById("center")
非要写里面的话直接写就行了,不过要卸载同一行上,每句后面+";"
参考技术C <div id="top" onclick="if(center.style.display=='none')center.style.display='block'elsecenter.style.display='none'"> 参考技术D 你这个"center"代表的是一个空间的id,或许你可以改动一下:<script language="javascript">
function tanchuan(center)

if(center.style.display=="none")

center.style.display="block"

else

center.style.display="none"


</script>

然后onclick="tanchuan(this)"

以上是关于JS:如何在onclick里写条件语句的主要内容,如果未能解决你的问题,请参考以下文章

如何在nuxt js中声明条件语句

if语句的案例

js中的条件语句和循环语句

用JS脚本如何实现多关键+多条件的查询(SQL语句)?

关于函数,条件语句,循环语句

Js的三种条件判断语句