如何使用 jquery 将文本分配给 asp 标签
我的页面中有一个 asp 标签。我喜欢用 jquery 在其中设置一些文本。
<asp:label id="lblError" runat="server" CssClass="error" />
我将使用哪种方法。
$(".error").text('hello');
or
$(".error").html('hello');
or
$(".error").val('hello');
我对这一切感到困惑?请帮忙。
i have a asp label in my page .i like to set some text in it with jquery .
<asp:label id="lblError" runat="server" CssClass="error" />
Which method will i use.
$(".error").text('hello');
or
$(".error").html('hello');
or
$(".error").val('hello');
i am confused with all this ?plz help .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的母版页或用户控件的 clientID 与您在 .aspx 页面中定义的不同,或者可能另一个元素共享相同的类,则另一种选择是:
具体回答问题,但如前所述< code>.text() 是最合适的选项,因为这 3 个选项都可以工作。使用
.text()
插入文本而不是.html()
从语义上来说是有意义的,因为您没有插入 HTML。就实际发生的情况而言,现在我想得更多了,这将是答案的另一部分,您可以通过检查 jQuery 脚本本身来看到这一点:
.text() 调用 javascript 函数
createTextNode
将字符串传入并附加到 DOM,几乎不执行任何其他操作。 //12 行代码.html() 对传入的字符串进行更多的清理/处理。还看起来有一些代码可以防止内存泄漏。还使用浏览器的
innerHTML
功能。 //38 行代码 关于.text()
和.html()
之间区别的最后一点,如 API 文档中所示,用于区分两者的这一行是:If you're using a master page or user control where the clientID will be different than what you defined in your .aspx page or possible that another element shares the same class, another option is:
To specifically answer the question though as noted already
.text()
is the most appropriate option as all 3 will work. It just semantically makes sense to use.text()
to insert text rather than.html()
since you are not inserting HTML.In terms of what actually happens would be another part of the answer now that I think about it a little more, and you can see this yourself by examining the jQuery script itself:
.text() calls javascript function
createTextNode
with the string passed in and appends to DOM and does little else. //12 lines of code.html() does more processing for cleaning/processing of the string that is passed in. Also looks to have some code in place to prevent memory leaks. Also uses the
innerHTML
function of the browser. //38 lines of codeOne last note on the difference between
.text()
and.html()
as seen on the API docs to differentiate the two is this line:我想说在这种情况下最合适的是
val(string)
它应该用于设置输入控制值html(string)
应该用于设置内部html 内容,而您只是分配纯文本。I'd say the most appropriate in this case is
val(string)
it's supposed to be used to set an input control valuehtml(string)
should be used to set inner html content and you're just assigning plain text.