2011-06-20 14 views
0

在我的網頁我有來源,看起來像這樣:我該如何做一個複雜的替代,使用JavaScript和jQuery?

<div id="opt_3" >A)</div> 
<div id="opt_2" >B)</div> 
<div id="opt_4" >C)</div> 
<div id="opt_5" >D)</div> 
<div id="opt_1" >E)</div> 

我需要的是建立一個的JavaScript運行時,需要這樣的事情作爲輸入VAR:

Text 1 word word word this is a text 3 word word. 

和變化它

<strong>E</strong> word word word this is a <strong>A</strong> word word. 

abc text 4 word 

,並改變它

abc <strong>C</strong> word 

我的javascript的工作將是採取字符串「文本X」或「文字X」內的數,看看相匹配的ID字段的第一個字符X的值並將該字符替換爲「文本X」。

我有jQuery加載。這可以幫助我給一些suggestioins?我是否需要使用JavaScript以及jQuery?

有人可以給我一些建議,關於如何做到這一點。我不是很熟悉JavaScript或jQuery。

+0

這是不一個答案,只是一個評論:JQuery是用Javascript編寫的庫。所以,如果你使用JQuery,你使用的是Javascript。 – Jason

+0

@Jason - 感謝您的評論。是的,也許我的問題不是很好。理想情況下,我想在jQuery的所有內容,但我認爲這太多了,即使jQuery看起來可以做很多事情。 –

+0

正如法提赫建議的那樣,如果可以的話,您應該使用「文本X」以外的內容。例如標籤。然後,選擇和更改樣式將非常容易。 – Jason

回答

0

爲此,您需要jQuery的


//get the original text 
txt = $('#text-container').text(); 
//split the whole text by the words "Text" 
// this way each string in the array arr will contain as its first member the number 
// without the splitting text 
arr = txt.split('Text'); 
answerText = ''; 
for(i=0; i < arr.size(); i++){ 
    words=arr[i].split(' '); //split by spaces 
    //the first word will be the number 
    nr = words[0]; 
    //then we look up the corresponding option, and substitute the number 
    words[0] = $('#opt_'+nr).text(); 
    //and rebuild the original text 
    answerText += words.join(' '); 
} 

1

你應該這樣

 
var myText = 'Lorem {0} Dolor {1} Amet is a {2} text.'; 

var textReplace = function(txt) { 
    for (var i = 0, ii = arguments.length - 1; i < ii; i++) { 
     txt = txt.replace('{' + i + '}', arguments[i + 1]); 
    } 
    return txt; 
} 

textReplace(myText, 'ipsum', 'sit', 'dummy'); 

此功能需要的參數。第一個是你想要以某種方式替換的文本。其他參數將在您的文本中被替換。我建議你使用大括號的包裝文本,而不是Text 4或其他。

我希望這會有所幫助。

+0

謝謝你的信任。我同意也許使用{1}更容易。我認爲你的代碼可以工作,但我不知道如何填充textReplace的爭論。這將取決於字段id =「opt_3」中數據的值。 –

+0

但是,還沒有一個[jQuery插件](http://api.jquery.com/category/plugins/templates/)或者這個確切的東西的方法嗎? – mplungjan

+0

@mplungjan,忘記使用jQuery插件做所有事情。這不是一個好方法。 – Fatih

1

下面的代碼應該做完全按照您描述:

var input = "Text 1 word word word this is a text 3 word word."; 
input = input.toLowerCase(); 
var split = input.split(" "); 
for(var i = 0; i < split.length; i++) { 
    if(split[i].toLowerCase() == "text") { 
     var num = split[i+1]; 
     var val = $("#opt_" + num).text(); 
     input = input.replace("text " + num, "<strong>" + val + "</strong>"); 
    } 
} 
alert(input); 

你可以看到它的工作here。它將你的字符串分割爲空格,然後循環遍歷數組,尋找單詞「text」的出現。當它找到一個時,它將用對應元素的值替換該單詞和下一個單詞(將根據您的指示將爲數字),並將其包裹在strong標記中。

+0

http://jsfiddle.net/m2j7u/ - 我也刪除右括號;-) – Alex

+0

@Alex - 謝謝你,錯過了位:) –

1

你可以做一個區分大小寫的正則表達式有一個回調函數代替,就像這樣:

function textReplace(v){ 
    return v.replace(/text ([0-9])/gi,function(i,e){ 
     return "<strong>"+$("#opt_"+e).text().substring(0,1)+"</strong>"; 
    }); 
} 

例如:http://jsfiddle.net/niklasvh/pLpxN/

相關問題