2014-02-21 41 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

相關問題