如何在类型为“”的输入上调用onclick函数;图像”;

How to call an onclick function on an input of type "image"?

本文关键字:调用 函数 图像 输入 onclick 类型      更新时间:2023-12-10

因此,在我的代码中,我有一个类型为"Image"的输入。

<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(event)事件处理程序内部,使用event.preventDefault()来阻止默认行为的发生(在您的情况下,表单正在提交到服务器)。

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

.hidden {
  display: none !important;
}

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