开发者

jquery get attribute value when property is not set

I simply want to get the current value of a field's attribute.

This field has a default value like:

<input validation="defaultValue" />

When i want to get the validation attribute, i don't know if it has been updated before or if this is still the default value.

So the property get with prop() return undefined when the property is not set (not yet updated), and the attr() method return always the default value (that's not true actually for maintainability but that will be in the future).

Is there a method that check:

if 开发者_如何学运维property is set => return property else return attribute

Thanks


This snippet will do:

var input = $("input");
var method = typeof input.prop("validation") != "undefined" ? "prop" : "attr";
input[method]("validation");

//Shortened to:
var input = $("input");
input[typeof input.prop("validation")!="undefined"?"prop":"attr"]("validation");

Explanation:

  • If the property is not set typeof ... "undefined", the "prop" string returns. Otherwise, the "attr" string returns.
  • This string is used to select the right method of the input object, either input["prop"] (=input.prop) or input["attr"] (=input.attr).
  • Finally, the method is invoked, passing "validation" as an argument, resulting in:
    1. The property (if existent) or
    2. The attribute (if the property doesn't exist).

I recommend to use data-validation instead of validation, to be HTML5-compliant.

Update: A JQuery method:

(function($){
    /* Defines the curProp method - Getting the current property
     * When the property exists, the prop method is used. Otherwise: attr */
    $.fn.curProp = function(name){
        return this[typeof this.prop(name) == "undefined" ? "attr" : "prop"](name);
    }
})(jQuery);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜