简体   繁体   English

单击按钮时如何将style.display从无更改为嵌入式?

[英]How do I change style.display from none to inline when button is clicked?

I want to display id="text" when the button is clicked. 我想在单击按钮时显示id="text" So I tried this: 所以我尝试了这个:

    <form name="i_choose_form" action="" method="post">
      <input type="submit" class="button" value="I am not sure, show me other choices..." onclick = "showText()"></br>
    </form>

    <span id ="text" style="display:none">First make your choice then you can see all other choices</span>

    <script type = "text/javascript">

function showText() { document.getElementById("text").style.display="inline"; }

</script>

But this does not work as expected and text is not displayed. 但这不能按预期方式工作,并且不会显示文本。 What am I doing wrong? 我究竟做错了什么? http://jsfiddle.net/dPhUQ/ http://jsfiddle.net/dPhUQ/

It is shown, but you are submitting the page. 它已显示,但是您正在提交页面。 Change your input to type='button' instead of 'submit' 将您的输入更改为type ='button'而不是'submit'

<input type="button" class="button" value="I am not sure, show me other choices..." onclick = "showText()"></br>

You are not cancelling the click event for the submit button so the page will submit the form. 您没有取消提交按钮的单击事件,因此页面将提交表单。

onclick = "showText(); return false;"

You should really look at adding the events unobtrusively . 你真的应该看看添加的事件悄悄地

<input type="submit" id="showMore" class="button" value="I am not sure, show me other choices..." onclick = "showText()">
<script type="text/javascript">
    function showText() { 
        document.getElementById("text").style.display="inline";
    }
    document.getElementById("showMore").click = showText;
</script>

The problem is the way you've got jsfiddle set up. 问题是您设置jsfiddle的方式。 On the left is a pull-down to choose how the site incorporates your JavaScript into the result page. 左侧是下拉菜单,用于选择网站如何将JavaScript合并到结果页面中。 Set it to "no wrap (head)" and it'll work. 将其设置为“ no wrap(head)”即可。 Well, it won't work, actually, but it'll call your function. 好吧,实际上它是行不通的,但是会调用您的函数。

The next problem you'll have is that your "submit" button will submit the form immediately after your handler runs. 下一个问题是您的“提交”按钮将在处理程序运行后立即提交表单。 To prevent that, you'll need to stop event propagation. 为防止这种情况,您需要停止事件传播。

看起来您的FORM正在干扰您想要的结果,请尝试以下操作:

<div onclick = "showText()">Click me</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM