开发者

Using custom keywords to set link in javascript

开发者 https://www.devze.com 2023-04-07 09:21 出处:网络
The script implications are more advanced, but I\'ve condensed it down to this following problem: In a nutshell I have some keyword variables set with javascript. These keyword variables contain URLs

The script implications are more advanced, but I've condensed it down to this following problem:

In a nutshell I have some keyword variables set with javascript. These keyword variables contain URLs. What I need is when a person inputs a keyword he will be taken to a specific URL. I've created a sample page illustrating my problem:

<a href=""  class="link">LINK</a><br>
<input type="text"  class="text" value="hallo" />
<input type="button" onclick="check();" value="Click ME">

<script type="text/javascript">
function check() {
    var key1 = "some_link1.com";
    var key2 = "some_link2.com";
    var key3 = "some_link3.com";

    var l = document.getElementsByClassName("link")[0];
    var t = document.getElementsByClassName("text")[0];
    if (t.value == "key1" || t.value == "key2" || t.value == "key3") {
        l.href = t.value;
        alert(t.value);
    } }</script>

The problem lies between the ** because the script must recognize that the value corresponds to the variable and use thet value instead. However currently I'm only getting the inputted value. By the way I can't use a form or开发者_如何学Python reload the page. It has to happen "live".

Any thoughts?

PS. the script is not meant to run, but to illustrate my point: http://jsfiddle.net/UhgKG/3/


Partly because I avoid eval() when there are other ways, but also because it just seems cleaner, is more extensible and is less code, I'd do it like this with an object lookup rather than the separate variables, the multiple if tests and the eval:

<a href="" id="link">LINK</a><br>
<input type="text" id="text" value="hallo" />
<input type="button" onclick="check();" value="Click ME">

<script type="text/javascript">
function check() {
    var keys = {
        key1: "some_link1.com",
        key2: "some_link2.com",
        key3: "some_link3.com"
    };

    var l = document.getElementById("link");
    var t = document.getElementById("text").value;
    if (t in keys) {
        l.href = keys[t];
        alert(t);
    }
}
</script>


<a href="" id="link">LINK</a><br>
<input type="text" id="text" value="hallo" />
<input type="button" onclick="check();" value="Click ME">

<script type="text/javascript">
function check() {
    var key1 = "some_link1.com";
    var key2 = "some_link2.com";
    var key3 = "some_link3.com";

    var l = document.getElementById("link");
    var t = document.getElementById("text").value;
    if (t == "key1" || t == "key2" || t == "key3") {
        l.href = eval(t); // no risk as we run this line if and only if the value is one of the options defined in the if
        alert(t);
    }
}
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号