【问题标题】:How to call an onclick function on an input of type "image"?如何在“图像”类型的输入上调用 onclick 函数?
【发布时间】:2015-04-18 10:09:23
【问题描述】:

所以,在我的代码中,我有这个“图像”类型的输入。

<div class="icon" id="button_dictionary">
    <form>
        <input class="buttonDictionary" type="image" src="icone_dicionario.jpg" value="" id="inputDictionary"> 
        <label for="inputDictionary">Dictionary</label>
    </form>
</div>

我希望,当用户点击它时,会出现以下表单:

<form action="http://www.google.pt/search" id="form-dictionary">
     (...)
</form>

我已经制作了一个 Javascript 函数来实现它:

function showsDictionaryForm(){
            if(document.querySelector('#form-dictionary').style.display == "none")
                document.querySelector('#form-dictionary').style.display = "inline-block";
            else
                document.querySelector('#form-dictionary').style.display = "none";
}

问题是当我尝试处理 onClick 事件时,当它发生时,上面的函数会被调用。该函数运行良好,因为对于“提交”输入类型,它可以正常工作。

无效的解决方案:

我尝试过这样的事情:

document.querySelector('#button_dictionary').onclick = showsDictionaryForm;

还有这个,在函数末尾添加return false

 <input class="buttonDictionary" type="image" src="icone_dicionario.jpg" value="" id="inputDictionary" onClick="showsDictionaryForm()">

它们都没有很好地工作。形式出现,但消失得一样快。在我看来,表单是计算出来的,但是当提交按钮时,页面会重新加载类似的东西,然后它又消失了。

【问题讨论】:

  • 在你showsDictionaryForm() 中你设置了#form-dictionnario,但是你使用#form-dictionnary-Y,可以吗?
  • 抱歉,已编辑。将所有内容传递给英语时只是一个错误。

标签: javascript html css image html-input


【解决方案1】:

在您的 showsDictionaryForm(event) 事件处理程序中使用 event.preventDefault() 来阻止默认行为的发生(在您的情况下,表单正在提交到服务器)。

showsDictionaryForm 上,我建议使用类操作而不是内联样式。例如,您可以全局定义:

.hidden {
  display: none !important;
}

并使用它来显示/隐藏form-dictionary 表单。

【讨论】:

    猜你喜欢
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    相关资源
    最近更新 更多