我目前正试图用jquery操纵两种不同类型的控件(标签和输入)的内容。截至目前,我通过使用两个命令来完成此操作。
if(true)
{
myControl.text('@types.Text');
myControl.val('@types.Text');
}
是否有一个命令可以同时执行这两项操作?
旁注:我已经尝试了html()和append(),但我认为这些是text()和val()的变体
答案 0 :(得分:3)
我在我的JavaScript实用程序中使用了类似的东西
$.fn.setValue = function(val) {
return this.each(function() {
switch (this.tagName.toLowerCase()) {
case "input":
switch ($(this).attr("type").toLowerCase()) {
case "hidden":
case "password":
case "text":
$(this).val(val); break;
case "radio":
case "checkbox":
this.checked = val; break;
} break;
case "span":
case "button":
case "label":
$(this).html(val); break;
case "select":
case "textarea":
$(this).val(val); break;
}
});
};
然后你可以使用你的新功能几乎任何类型的元素,而不必担心它是什么。
var myControl = $('#someSelector');
myControl.setValue('@Types.text');
答案 1 :(得分:2)
你可以写自己的东西,比如:
$.fn.tval = function (value) {
if (this.is(':input:not(:checkbox):not(:radio)')) {
this.val(value);
}
else {
this.text(value);
}
return this;
}
答案 2 :(得分:0)
没有text()
与val()
合并的命令。为此编写自定义函数有什么问题吗?顺便说一下:虽然text()
和html()
几乎相同,但val()
和append()
非常不同 - 请查看jquery文档。
答案 3 :(得分:0)
如果你还想支持val()和text()的获取方:
$.fn.tval = function(value) {
if (value) {
if (this.is(':input:not(:checkbox):not(:radio)')) {
this.val(value);
} else {
this.text(value);
}
return this;
}else{
if (this.is(':input:not(:checkbox):not(:radio)')) {
return this.val();
} else {
return this.text();
}
}
}