javascript通过链接标题更改输入值 [英] javascript change input value by link title

查看:62
本文介绍了javascript通过链接标题更改输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript的新手,我需要一些有关我遇到的简单问题的帮助:

I'm new to JavaScript and I need some help with a simple problem I'm having:

我有一个空的输入字段,还有两个链接( anchors ),它们的 title 属性值各不相同.

I have one empty input field, and two links (anchors) with differing values for the title attribute.

我想编写一小段JavaScript,将 input 元素的值更改为用户单击的链接的标题.

I'd like to write a small piece of JavaScript that changes the value of the input element to the title of whichever link the user clicks.

例如:

第一个链接= 布拉格
第二个链接= 布达佩斯

当我单击布达佩斯"时,我希望 input 元素的值更改为布达佩斯"

When I click "Budapest" I'd like the value of the input element to change to "Budapest"

如果需要,我可以提供基本的 jsFiddle ,但希望我已经足够清楚了.

If needed I can supply a basic jsFiddle but hopefully I've made myself clear enough.

推荐答案

如果项目真的那么小,那么将一些 onclick 处理程序附加到锚点上可能会更容易,然后定义一个基本功能来更新输入元素.

If the project is really this small then it's probably easier to just attach some onclick handlers to your anchors, and then define a very basic function to update the input element.

HTML

<a href="#" title="Prague" onclick="updateValue(this.title, event);">Prague</a>
<a href="#" title="Budapest" onclick="updateValue(this.title, event);">Budapest</a>
<input type="text" id="country" name="country" value="" />

JavaScript

function updateValue(val, event) {
    document.getElementById("country").value = val;
    event.preventDefault();
}

示例: http://jsfiddle.net/zUVA5/

如果锚点很多,那么手动添加单个 onclick 处理程序将是一件很痛苦的事情,要避免这种情况,您只需将内容包装在一个包含元素中,然后应用以编程方式单击事件处理程序以访问所有嵌套的锚点:

If you have a large amount of anchors then adding individual onclick handlers by hand would be quite a pain, to avoid this you can simply wrap your content in a containing element and then apply click event handlers to all nested anchors programmatically:

示例: http://jsfiddle.net/FUvYC/

这篇关于javascript通过链接标题更改输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆