我创建了一个名为 val2 的 Jquery 插件,它检测跨度与输入,并且只是整理出何时使用 $().text() 与 $().val()。在跨度上使用 val() 并想知道为什么它被打破只是为了拍前额并说,“当然,哑……它是跨度!” 我创建了这个插件:
$.fn.val2 = function (newVal) {
// Jquery Plugin to improve upon $().val() and agnostically handle get/set of values for a span or input (type="text")
// http://learn.jquery.com/plugins/basic-plugin-creation/
// use, get mode: var val = $("#" + id).val2();
// use, set mode: $("#" + id).val2("fred");
if (this !== undefined) {
// newVal indicates set vs get mode
if (newVal === undefined) {
var ret = "";
if (this.attr("value") === undefined && this.prop("value") === undefined)
ret = this.text(); // this is a span
else
ret = this.val(); // this would be an input
return ret;
}
else {
if (this.attr("value") === undefined && this.prop("value") === undefined)
this.text(newVal); // this is a span
else
this.val(newVal); // this would be an input
}
}
};
用法示例:
获取方式:
var txt = $("#MySpan").val2();
var txt = $("#MyInput").val2();
设置模式:
$("#MySpan").val2("fred");
$("#MyInput").val2("fred");