根据链接的内容更改输入字段值
Change input field value depending on what a link has
我有一个总是在变化的链接,我希望它根据链接指向的位置将一些文本打印到输入文本字段中。例如,我的链接可能如下所示。
<a onclick="main()" id="link" href="#foo">
或者同一个链路有时可能看起来像
<a id="link" href="#bar">
如果链接链接到#foo,那么我希望以下内容看起来像
<input id="input" type="text" value="Hello World" />
如果链接链接到#bar,那么我需要输入Good Bye World的值。
怎么能做到这一点。我尝试了以下操作,但我认为它不起作用,因为URL在用户点击它之前不会改变。所以它正在寻找一些还没有出现的东西。
function main() {
var url = window.location.href;
if (url.search("#foo") > 0) {
document.getElementById("link").value = "#foo";
document.getElementById("input").value = "Hello World";
}
}
UPDATE以下是一个链接可能是的一些哈希标签的列表。以及单击链接时输入文本字段的内容。
#work = Can't talk I'm at work
#home = I have kids I still can't talk
#bar = I'm busy getting drunk I can't talk
#bathroom = Listen you perv I'm not interested don't you get it.
但请记住,该网站最初位于example.com。它有一个链接,可以链接到上面的任何哈希标签。当用户根据链接href的哈希标签点击该链接时,将决定在输入字段中输入什么。
这应该可以工作,但您不能用jsfiddle测试它。希望这能帮助你理解。
JS:
document.getElementById('link').onclick = function () {
var url = window.location.href;
if (url.indexOf("#foo") > -1) {
document.getElementById("link").innerHTML = "#foo";
document.getElementById("input").value = "Hello World";
}
}
HTML:
<a id="link" href="#foo">link</a>
<input id="input">
您是否试图检查当前URL的哈希部分,如果是,那将是location.hash
,如果您试图检查单击链接的实际属性,您可能应该使用getAttribute
?
function main() {
var hash = window.location.hash,
inp = document.getElementById("input");
if (hash == '#foo') {
inp.value = "Hello World";
}else if (hash == '#bar') {
inp.value = "Goodbye World";
}else{
inp.value = "Stick a fork in me";
}
}
当然,您必须关闭这些锚点并拥有有效的标记!
编辑:
你可以去掉内联onclick,只做:
$(window).on('hashchange', main);
将文本的id输入到"hello"并执行以下
function main(){
if(url.indexOf("foo") != -1){
document.getElementById("hello").value = "Hello World foo";
}else{
document.getElementById("hello").value = "Hello World bar";
}
}
<input type="text" id="hello" value="Hello World" />
相关文章:
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 而循环只设置php中输入字段中的第一个值
- 在输入字段中将最小金额设置为
- 如何在输入字段中的按钮的帮助下打开日历,该字段的类型为“=”;日期”;
- 如何在HTML输入字段中添加不可删除的后缀
- 互斥单选按钮和相应的输入字段
- 在IE9中的输入字段中输入焦点最近按钮
- 选中单选框时将属性添加到输入字段
- 当设置addFromAutocompleteOnly时,剩余文本将保留在输入字段中
- 我如何在数字插入中使用逗号,这样它就不会'不要破坏我的输入字段
- 在输入字段上有两个函数调用,一个在Blur上,一个不在Angular中
- 输入字段将't获取更新的值
- 如何选择多个输入字段并删除所需的属性
- 输入字段,只接受0到12之间的数字
- 单击鼠标,用MySQL数据填充html表单输入字段
- 使用jquery将输入字段转换为文本
- Model中的Typeahead返回空值以形成输入字段
- 如何从查询字符串中的输入字段发回文本
- 如何验证日期、月份和日期的3个独立输入字段;年使用jquery或javascript
- 将值传递给jquery创建的输入字段