jQuery自动检测我是否需要使用.html()或.val()

Ala*_*blo 10 jquery

我正在编写一个jquery插件来创建为我的应用程序设计的ajax调用.

在这个插件中,我的ajax调用看起来像这样(减少到问题需要):

    $.ajax({
        url: route,
        type: "post",
        data: inputData,
        success: function(response, textStatus, jqXHR) {
            if (outputSelector !== undefined) {

                $(outputSelector).html(response);
                // or
                $(outputSelector).val(response);

            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

outputSelector是一个在插件外部定义的选择器.我不知道这个选择器是a <div>还是a <input>甚至是a <select>.有没有一种聪明的方法可以知道我是否需要使用val()或html()?

Vis*_*ioN 13

可能我们可以检查该元素是否具有value属性:

var el = $(outputSelector);
if (el[0].value !== undefined) {
    el.val(response);
} else {
    el.html(response);
}
Run Code Online (Sandbox Code Playgroud)

所以,有点像一线通用解决方案可能是:

$(outputSelector).each(function() {
    this[this.value !== undefined ? "value" : "innerHTML"] = response;
});
Run Code Online (Sandbox Code Playgroud)