2011-06-06 49 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); 
     } 
    });