javascript将控件名称作为函数参数传递

时间:2013-07-16 08:29:39

标签: c# javascript asp.net function

我正在尝试将一些控件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;
        }

3 个答案:

答案 0 :(得分:1)

由于ids是变量,因此不应将其与""

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

您还需要更改

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

因为TextBox1TextBox2都必须作为字符串传递

答案 1 :(得分: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;
        }

答案 2 :(得分:0)

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

如果它有帮助,试试这个。