使用 href 调用 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6557357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:05:35  来源:igfitidea点击:

Call javascript function with an href

javascript

提问by Cláudio Ribeiro

i'm developing a website, but i'm not an expert when it comes to javascript. I'm using a script that i found on the internet for searching the page for a text string. To call this function i use the following code:

我正在开发一个网站,但在 javascript 方面我不是专家。我正在使用我在互联网上找到的脚本来搜索页面中的文本字符串。要调用此函数,我使用以下代码:

  <div class="pesquisa" id="pesquisa"><form name="f1" action=""
  onSubmit="if(this.t1.value!=null && this.t1.value!='')
  findString(this.t1.value);return false">
  <input name="t1" type="text" /></form>
  </div>

this is working well, when i enter text and click enter he finds it on the page. Now i have a "button" next to it that is represented by:

这运行良好,当我输入文本并单击 Enter 时,他会在页面上找到它。现在我旁边有一个“按钮”,表示为:

<a href='javaScript:document.f1.findString(this.t1.value)'>
<div class="enviar" id="enviar">Pesquisar</div></a></div>

I want this "button" to call the same function with the value inserted in the form. But it is not working this way. Any ideas on how this can be made ?

我希望这个“按钮”使用表单中插入的值调用相同的函数。但它不是这样工作的。关于如何做到这一点的任何想法?

Thanks in advance, Cláudio

提前致谢,克劳迪奥

回答by FishBasketGordo

First, add an idattribute to the textbox:

首先,id向文本框添加一个属性:

<input id="t1" name="t1" type="text" />

Then, in your <a>tag, you can do this:

然后,在您的<a>标签中,您可以执行以下操作:

<a href="#" onclick="findString(document.getElementById('t1').value); return false;">Click Me</a>

回答by Kon

Try this.. Add an id attribute to t1 (also called "t1"), and then reference it like this:

试试这个.. 向 t1(也称为“t1”)添加一个 id 属性,然后像这样引用它:

<a onclick="javaScript:findString(document.getElementById('t1').value)">