2011-06-06 50 views
0

字符串文本跨度,如果我在$(this).text(temp);"something"它的工作原理更換temp,改變span文本,但是當我使用一個string.format它不工作。替換在下面的代碼jQuery的

jquery code:

var x = $("span.resource");   
    x.each(function() {    
     if ($(this).attr('id') = "l1") { 
      var temp = String.Format("{0}/{1}", variable1,variable2); 
      $(this).text(temp); 
     }); 
+0

'variable1'和'variable2'從哪裏來? – mekwall 2011-06-06 09:09:36

+0

您可能會發現[此鏈接](http://stackoverflow.com/questions/610406/javascript-printf-string-format)有用,也可能發現使用'id = l1'找到元素效率更高'$('#l1')' – jaime 2011-06-06 09:12:28

+0

另外,如果你看一下[MDC](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String),那麼沒有名爲'Format'的方法'String'對象。你可能會混淆語言嗎? ;) – mekwall 2011-06-06 09:14:48

回答

1

如果你看一下MDC沒有爲String對象命名Format方法。我的猜測是你是混亂的語言(JavaScript和C#),這對於多語言開發者來說很常見。

但是,一切都沒有丟失。通過添加到String對象的原型,您可以輕鬆地在JavaScript中重新創建等效的方法。積分去gpvos,Josh Stodola,無限和Julian Jelfs誰貢獻these solutions to a similar problem

String.prototype.format = function(){ 
    var args = arguments; 
    return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; }); 
}; 

稍加調整就應該像這樣工作:

$("span.resource").each(function(){ 
    if (this.id == "l1") { 
     var $this = $(this), 
      newText = $this.text().format(var1, var2); 
     $this.text(newText); 
    } 
}); 

布萊爾Mitchelmore有similar implementation on his blog,但也有一些額外的功能和附加功能。你可能也想檢查一下!

0

你有語法錯誤,的String.Format不會在JavaScript存在。這工作:

$("span.resource").each(function() {    
     if ($(this).attr('id') == "l1") { 
      var temp = variable1 + '/' + variable2; 
      $(this).text(temp); 
     } 
    });