如何在jquery集合日期中传递变量

本文关键字:变量 日期 集合 jquery | 更新日期: 2023-09-27 18:26:54

我正在尝试使用C#执行一些JS代码:

executor.ExecuteScript("window.document.getElementById('pmtDate').setAttribute('value','08/16/2013');");

我希望传递Date的变量,而不是08/16/2013

谁能告诉我这个的语法吗?

如何在jquery集合日期中传递变量

var temp_date='08/16/2013';
executor.ExecuteScript("window.document.getElementById('pmtDate').setAttribute('value',tempdate);");

我的理解是,您想要mm/dd/yyyy格式的日期。要获取当前日期,请使用以下代码:

var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var today = (month<10 ? '0' : '') + month + '/' + (day<10 ? '0' : '') + day + '/' + d.getFullYear();

现在将其用于您的代码。

executor.ExecuteScript("window.document.getElementById('pmtDate').setAttribute('value',"+today+");");

如果我说对了:

executor.ExecuteScript("var date = '08/16/2013'; window.document.getElementById('pmtDate').setAttribute('value',date);");

实现这一点主要有两种技术。一种是字符串串联,另一种是串插值

连接

var theDate = "8/16/2013";    
var theCommand = "window.document.getElementById('pmtDate').setAttribute('value'," + theDate + ");"
executor.ExecuteScript(theCommand);

插值

var theDate = "8/16/2013";
var theCommand = String.Format("window.document.getElementById('pmtDate').setAttribute('value', {0});", theDate);
executor.ExecuteScript(theCommand);

如果您使用Selenium,您还可以向函数传递一个参数数组:

var theDate = "8/16/2013";
var theCommand = "window.document.getElementById('pmtDate').setAttribute('value', arguments[0]);";
executor.ExecuteScript(theCommand, new object[] { theDate });

试试这个:

var currentDate = new Date();
window.document.getElementById('pmtDate').setAttribute('value', getDate());

function getDate(){
    return currentDate.toString();
}

Fiddle

更新答案:

executor.ExecuteScript("function getDate(){return currentDate.toString();}var currentDate = new Date();window.document.getElementById('pmtDate').setAttribute('value', getDate());");