简体   繁体   English

asp.net 文本框动态创建用.CssClass属性

[英]asp.net textbox dynamic creation with .CssClass attribute

I am having a scenario by which I have to dynamically create the form based on the user selection.我有一个场景,我必须根据用户选择动态创建表单。 In the form, there are few textboxes which should be added at the end to the Total Textbox.在表单中,有几个文本框应该添加到 Total Textbox 的末尾。

The way I am distinguishing the textboxes to be added at the end is by specifying as below..我区分最后添加的文本框的方式是通过如下指定..

TextBox txt1 = new TextBox();
        txt1.ID = "txt1";
        txt1.CssClass = "addToTotal";

        TextBox txt2 = new TextBox();
        txt2.ID = "txt2";
        txt2.CssClass = "addToTotal";

        TextBox txt3 = new TextBox();
        txt3.ID = "txt3";
        txt3.CssClass = "txtTotalPoints";

        PlaceHolder1.Controls.Add(txt1);
        PlaceHolder1.Controls.Add(txt2);
        PlaceHolder1.Controls.Add(txt3);

In reality, there is no css class named 'addToTotal' in the site css file .实际上, site css file中没有名为'addToTotal'的 css class 。 It's just used as a flag to notify me for adding at the end.它只是用作一个标志来通知我在最后添加。

Is it a good practice to add a.CssClass even though the actual class does not exist.即使实际的 class 不存在,添加 a.CssClass 是否是一种好习惯。 Are there any pitfalls in using this methodology?使用这种方法有什么陷阱吗?

I would assume that the overhead of using a CSS class which does not exist as a marker is minimal, so I wouldn't change your implementation based on that.我假设使用不作为标记存在的 CSS class 的开销很小,所以我不会基于此更改您的实现。 If you're concerned about best practices - which you could rightly be, CSS classes were never intended to be used like this - you could add a data-* attribute to the input and use that instead:如果您担心最佳实践-您可能是正确的,CSS 类从未打算像这样使用-您可以向输入添加data-*属性并改用它:

txt2.Attributes["data-addToTotal"] = "true";

...then finding those elements with JQuery: ...然后使用 JQuery 找到这些元素:

$("input[data-addToTotal='true']")

data-* attributes are part of HTML5 , but are fully backwards compatible. data-*属性是HTML5的一部分,但完全向后兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM