当属性未设置时,jQuery获取属性值 [英] jquery get attribute value when property is not set

查看:97
本文介绍了当属性未设置时,jQuery获取属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想获取字段属性的当前值.

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

此字段的默认值为:

<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.

因此,当未设置(尚未更新)该属性时,该属性与prop()一起返回undefined,并且attr()方法始终返回默认值(对于可维护性而言,这实际上不是正确的,但是它将保留在默认值中).未来).

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).

有没有一种检查方法:

如果设置了属性=>返回属性 否则返回属性

if property is set => return property else return attribute

谢谢

推荐答案

此代码段将执行以下操作:

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");

说明:

  • 如果未设置属性typeof ... "undefined",则返回"prop"字符串.否则,返回"attr"字符串.
  • 此字符串用于选择input对象的正确方法,input["prop"](= input.prop)或input["attr"](= input.attr).
  • 最后,调用方法,将"validation"作为参数传递,结果为:
  • 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. 属性(如果存在)
  2. 属性(如果属性不存在).

为了兼容HTML5,我建议使用data-validation而不是validation.

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

(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);

这篇关于当属性未设置时,jQuery获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆