0

我正在尝试将一些控件 ID 从后面的代码传递给 html,但我事先不知道控件名称,因为它们是动态创建的,因此我不能使用这样的东西:MyTextBox = document.getElementById("<%= TextBox1.ClientID %>");

我怎样才能使以下代码工作(如果可能的话):

            TextBox test = ((TextBox)e.Row.Cells[7].Controls[0]);
            test.ID = "TextBox1";
            TextBox test2 = ((TextBox)e.Row.Cells[8].Controls[0]);
            test2.ID = "TextBox2";
            test.Attributes.Add("onChange", "javascript:MyFunc(TextBox1, TextBox2);");

JS函数:

function MyFunc(TextBox1,TextBox2) {
            MyTextBox = document.getElementById("TextBox1");
            MyTextBox2 = document.getElementById("TextBox2");

            var splitDate = MyTextBox.value.split('/');
            var date = new Date(splitDate[2], splitDate[1] - 1, splitDate[0]);

            var day = date.getDate();
            var month = date.getMonth() + 1;
            var year = date.getFullYear() + 1;
            if (day < 10) {
                day = '0' + day;
            }
            if (month < 10) {
                month = '0' + month;
            }

            MyTextBox2.value = day + "/" + month + "/" + year;
        }
4

3 回答 3

1

由于 id 是变量,因此不应将其括在""

var MyTextBox = document.getElementById(TextBox1);
var MyTextBox2 = document.getElementById(TextBox2);

你也需要改变

test.Attributes.Add("onChange", "javascript:MyFunc('TextBox1', 'TextBox2');");

因为两者都TextBox1必须TextBox2作为字符串传递

于 2013-07-16T08:33:47.243 回答
0
test.Attributes.Add("onChange", "javascript:MyFunc(" + TextBox1.ClientID + ", " + TextBox2.ClientID + ")");

如果有帮助,试试这个。

于 2013-07-16T08:47:39.410 回答
0

我认为你可以这样做,

 TextBox test = ((TextBox)e.Row.Cells[7].Controls[0]);
            test.ID = "TextBox1";
            test.Attributes.Add('class','TextBox1');
            TextBox test2 = ((TextBox)e.Row.Cells[8].Controls[0]);
            test2.ID = "TextBox2";
            test.Attributes.Add('class','TextBox2');
            test.Attributes.Add("onChange", "javascript:MyFunc(TextBox1, TextBox2);");

在 JS 中:

function MyFunc(TextBox1,TextBox2) {
            MyTextBox = document.getElementByClass("TextBox1");
            MyTextBox2 = document.getElementByClass("TextBox2");

            var splitDate = MyTextBox.value.split('/');
            var date = new Date(splitDate[2], splitDate[1] - 1, splitDate[0]);

            var day = date.getDate();
            var month = date.getMonth() + 1;
            var year = date.getFullYear() + 1;
            if (day < 10) {
                day = '0' + day;
            }
            if (month < 10) {
                month = '0' + month;
            }

            MyTextBox2.value = day + "/" + month + "/" + year;
        }
于 2013-07-16T08:39:31.157 回答