2014-02-21 38 views
1

我有一个变量被设置为一个<div />jQuery的 - 显示变量,而不是文本字符串

.html();变量是另一个变量的名称。我希望它显示其他变量的内容,但它只是显示其他变量的名称。

我该如何强制它显示变量内容而不是文本字符串?

var clothing = 'dogeshop cryptoshop doge_clothing fyrstikken the_molly_machine peace_and_love moolah_market shibe_swag undieguys urban_graff kravshop got_doge mean_elephant the_dogedoor_store'; 


setInterval(function() { 
    var term = $("input").val(); 
    $("#results").html(term); 
}, 100); 

当用户键入“服装”到$("input");的“服装”变量的内容应在$("#results");<div />被显示。相反,它只是说'衣服'。

+1

我不认为这是正确的机制。为什么不使用关联数组而不是变量?所以你可以查看字符串''''(从'$(“input”)。val()')获得并检索''dogeshop cryptoshop ...'')? – lurker

回答

1

另一种方法是使用对象的属性,这样

var obj = {}; 
obj.clothing = 'dogeshop cryptoshop doge_clothing fyrstikken the_molly_machine peace_and_love moolah_market shibe_swag undieguys urban_graff kravshop got_doge mean_elephant the_dogedoor_store'; 


setInterval(function() { 
    var term = $("input").val(); 
    $("#results").html(obj[term]); 
}, 100); 

这里的小提琴:http://jsfiddle.net/ZL7EQ/

+0

这是最好的答案,谢谢! – william44isme

0

我在使用jQuery时自己犯这个错误。

尝试,而不是:

$("#results").text(term); 

不知道你有时间间隔。您可以使用更改事件更改#results

+0

似乎没有工作,结果和以前一样。 – william44isme

+0

results.text不是html :) – alexmac

+0

是的,我尝试过,但它似乎仍然不工作。 [jsFiddle](http://jsfiddle.net/LyQqg/) – william44isme

1

http://jsfiddle.net/z29AR/

var clothing = 'dogeshop cryptoshop doge_clothing fyrstikken the_molly_machine peace_and_love moolah_market shibe_swag undieguys urban_graff kravshop got_doge mean_elephant the_dogedoor_store'; 

$('input:text').on('input', function() { 
    var term = $("input").val(); 
    if (term == 'clothing'){ 
     $("#results").html(clothing); 
    } 
}); 
+0

该解决方案几乎不能扩展到2个条目。 – Mathletics

+0

Upvote,因为它确实解决了问题,但确实太僵化了。将来我会有许多变数来搜寻。谢谢反正:) – william44isme

1

我知道如何解决这个问题是使用eval的唯一方法:

$("#results").html(eval(term)) 

但你真的shouldn't want to do that。 :)

+0

为什么不呢?完美的作品,谢谢! – william44isme

+3

@ rla4,@ william44isme在用户输入上使用'eval()'是一个很大的安全问题! – Skwal

+0

刚刚编辑我的答案,并添加一个链接解释为什么不。请记住,它有很多隐患,并明智地使用它 – rla4

1

使用字典。

// store strings in an object so you can look them up by key 
var dict = { 
    clothing: 'dogeshop ...', 
    anotherKey: '...' 
}; 

// update the result when the input changes 
$('input').on('change', function() { 
    var result = dict[this.value]; // make sure the key exists 

    if (result) { 
     $('#results').val(result); // update the results 
    } 
}); 
+0

哇!这太棒了,谢谢你通过删除间隔来优化代码。 – william44isme

相关问题