根据链接的内容更改输入字段值

Change input field value depending on what a link has

本文关键字:输入 字段 链接      更新时间:2023-09-26

我有一个总是在变化的链接,我希望它根据链接指向的位置将一些文本打印到输入文本字段中。例如,我的链接可能如下所示。

<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" />