c# - 在 C# 和 ASP.NET 的 javascript 警报中使用 %s

标签 c# javascript asp.net

我有一个 XML 文件,其中包含一个简单的节点,例如:

<question lang='en'>Do you want to buy %s from us ?</question>
<question lang='fr'>Voulez-vous acheter chez nous cette %s ?</question>

我有一个 C# 库(使用 ASP.NET),它根据用户语言获取节点值。

我想在 javascript 警报中使用文本

var test = '<%=Language.GetString(Question.EN) %>';

我想通过在 javascript 中调用类似的 sprintf 来在警告对话框中显示以下内容。

或者我必须使用这个插件:http://www.diveintojavascript.com/projects/javascript-sprintf

谢谢

最佳答案

您可以使用 String.prototype 将新函数添加到 String 类型 ( JSFiddle demo ):

String.prototype.sprintf = function(){
    // if argument list is empty
    // return this as new string
    if(arguments.length === 0)
        return this;

    // copy all arguments except the first one
    var newArgs = [].slice.call(arguments,1);    

    // Replace %d, %s, %f, %l, %u with first argument
    var tempString = this.replace(/%[dsflu]/,arguments[0]);

    // call again until all arguments are used
    return tempString.sprintf.apply(tempString,newArgs);
};

var testString = "%s! Do you want to use %s?";
document.write(testString.sprintf("Hello","String.prototype.sprintf"));

关于c# - 在 C# 和 ASP.NET 的 javascript 警报中使用 %s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9733721/

相关文章:

Javascript document.getElementsByName() 函数对我来说很奇怪

Javascript 错误 - 无法调用 null 的方法 'appendChild' (svgicons)

c# - ASP.NET Core 3.1 中基于角色的授权,带有 Identity 和 ExternalLogin

javascript - 如何在 ASP.NET 中对图像源 url 进行哈希处理

c# - 阻止应用程序在终止进程时关闭屏幕

c# - 有没有办法使用反射在结构实例上设置属性?

c# - asp.net C# 数据库表列列表

javascript - 未获取单击的 href 标签的索引值

c# - 如何将 Crystal 报表绑定(bind)到手动创建的DataSet

c# - 使用 Linq to SQL SELECT @@DBTS