开发者

replace span text with a string with jquery

in below code if i replace temp in $(this).text(temp); with "something" it works and change span text, but when i use a s开发者_C百科tring.format it doesn't work.

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);
       });


If you look at MDC there's no method named Format for the String object. My guess is that you are confusing languages (JavaScript and C#), which is quite common for multi-language developers.

However, everything's not lost. You can easily recreate an equivalent method in JavaScript by adding to the prototype of the String object. Credits go to gpvos, Josh Stodola, infinity and Julian Jelfs who contributed to these solutions to a similar problem.

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

With a little tweaking it should work like this:

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

Blair Mitchelmore have a similar implementation on his blog, but with some extra features and added functionality. You might want to check that out as well!


You had syntax errors, and String.Format doesn't exist in javascript. This works:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜