• 【jQuery源码】html,text,val


    jQuery封装的方法html,text,val

    1. .html()用为读取和修改元素的HTML标签
    2. .text()用来读取或修改元素的纯文本内容
    3. .val()用来读取或修改表单元素的value值

    一、html()

    1.取值

    获取集合中第一个匹配元素的HTML内容

    在一个 HTML 文档中, 我们可以使用 .html() 方法来获取任意一个元素的内容。 如果选择器匹配多个元素,那么只有第一个匹配元素的 HTML 内容会被获取

    源码部分可见jQuery.access在属性节点操作的时候就详解过了,就是合并分解多个参数,细分到每一个流程调用中,通过回调接收分解后的参数

    可见针对nodeType === 1的节点是通过浏览器接口innerHTML返回需要取的值

    有些浏览器返回的结果可能不是原始文档的 HTML 源代码。例如,如果属性值只包含字母数字字符,Internet Explorer有时丢弃包裹属性值的引号。

    复制代码
    html: function( value ) {
            return jQuery.access( this, function( value ) {
                var elem = this[ 0 ] || {},
                    i = 0,
                    l = this.length;
    
                if ( value === undefined && elem.nodeType === 1 ) {
                    return elem.innerHTML;
                }
            }, null, value, arguments.length );
    复制代码

    2.设值

    .html() 方法对 XML 文档无效.

    我们可以使用 .html() 来设置元素的内容,这些元素中的任何内容会完全被新的内容取代。

    此外,用新的内容替换这些元素前,jQuery从子元素删除其他结构,如数据和事件处理程序,防止内存溢出

    复制代码
    if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
        !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
        value = value.replace( rxhtmlTag, "<$1></$2>" );
        try {
            for ( ; i < l; i++ ) {
                elem = this[ i ] || {};
    
                // Remove element nodes and prevent memory leaks
                if ( elem.nodeType === 1 ) {
                    jQuery.cleanData( getAll( elem, false ) );
                    elem.innerHTML = value;
                }
            }
            elem = 0;
            // If using innerHTML throws an exception, use the fallback method
        } catch( e ) {}
    }
    复制代码

    对插入的值做一下过滤处理

    必须是字符串,而且不能暴行script|style|link,并且不是tr,表格等元素

    最后通过innerHTML覆盖节点,防止内存溢出需要jQuery.cleanData清理节点上的事件与数据

    3.总结

    elem.innerHTML 也就是从对象的起始位置到终止位置的全部内容,包括Html标签。

    二、text()

    1.取值

     jQuery.text( this ) 实际调用Sizzle.getText

    复制代码
    if ( typeof elem.textContent === "string" ) {
                        return elem.textContent;
                    } else {
                        // Traverse its children
                        for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
                            ret += getText( elem );
                        }
                    }
    复制代码

    但是实际上jQuery没有用innerText获取文本的值,而采用的是textContent来兼容火狐下innerText不能用的问题。

    2.设值

    考虑下,如果文本的值不仅仅是字符串,可能是带有标签的

    '<p>This is a test.</p>'

    这种情况下,当然就不能直接套用 elem.textContent = '<p>This is a test.</p>'

    我们必须意识到这种方法提供了必要的字符串从提供的正确的HTML中脱离出来。

    jQuery这样做, 他调用DOM 方法.createTextNode(), 一种替代的特殊字符与HTML对应(比如< 替换为 &lt; )方法

    看代码

    this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) );

    通过empty,先清理该节点上的事件与内容

    // Prevent memory leaks
                        jQuery.cleanData( getAll( elem, false ) );
                        // Remove any remaining nodes
                        elem.textContent = "";

    通过createTextNode处理,调用append

    3.总结

    .text() 取值时采用textContent,赋值时采用createTextNode

    .text() 方法不能使用在 input 元素或scripts元素上。 input 或 textarea 需要使用 .val() 方法获取或设置文本值。得到scripts元素的值,使用.html()方法

    三、.val()

    获取匹配的元素集合中第一个元素的当前值或设置匹配的元素集合中每个元素的值。

    .val()方法主要用于获取表单元素的值,比如 inputselect 和 textarea

    对于选择框和复选框,您也可以使用:selected 和 :checked选择器来获取值,

    1.取值

    复制代码
    hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
    
                        if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
                            return ret;
                        }
    
                        ret = elem.value;
    
                        return typeof ret === "string" ?
                            // handle most common string cases
                            ret.replace(rreturn, "") :
                            // handle cases where value is null/undef or number
                            ret == null ? "" : ret;
    复制代码

    select为例

    <select multiple="multiple"> 元素, .val()方法返回一个包含每个选择项的数组,如果没有选择性被选中,它返回null

    html代码,multiple="multiple" 多选项,如果只是单选,只用用ele.value即可了

    复制代码
    <select size="10" multiple="multiple" id="multipleselect" name="multipleselect">
        <option>XHTML</option>
        <option>CSS</option>
        <option>JAVASCRIPT</option>
        <option>XML</option>
        <option>PHP</option>
        <option>C#</option>
        <option>JAVA</option>
        <option>C++</option>
        <option>PERL</option>
    </select>
    复制代码

    js代码

    var p = $("#multipleselect")
         p.change(function(){
             console.log( p.val());
         });

    image

    针对多选的情况,jQuery要如何处理?

    引入了jQuery.valHooks,修正了在不同情况下表单取值的bug,其中就有针对select的set与get的处理

    image

    针对多选的hack

    复制代码
    for ( ; i < max; i++ ) {
                            option = options[ i ];
    
                            // IE6-9 doesn't update selected after form reset (#2551)
                            if ( ( option.selected || i === index ) &&
                                // Don't return options that are disabled or in a disabled optgroup
                                ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
                                ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
    
                                // Get the specific value for the option
                                value = jQuery( option ).val();
    
                                // We don't need an array for one selects
                                if ( one ) {
                                    return value;
                                }
    
                                // Multi-Selects return an array
                                values.push( value );
                            }
                        }
    复制代码

    遍历所有的option元素,找到对应的value

    复制代码
    option: {
                    get: function( elem ) {
                        // attributes.value is undefined in Blackberry 4.7 but
                        // uses .value. See #6932
                        var val = elem.attributes.value;
                        return !val || val.specified ? elem.value : elem.text;
                    }
                }
    复制代码

    如果是多选

    values.push( value ); 

    返回合集

    2.设值

    同样的处理类似,通过jQuery.valHooks找到对应的处理hack

    否则直接 this.value = val;

  • 相关阅读:
    POJ 3093 Margaritas on the River Walk(背包)
    BZOJ 2287 【POJ Challenge】消失之物(DP+容斥)
    WC2017 Day1
    WC2017 Day0
    WC2017 Conclusion
    WC2017 Day6
    UOJ #58 糖果公园
    WC2017 Day5
    codevs 1946 阿狸的打字机
    HDU 2457 DNA_repair
  • 原文地址:https://www.cnblogs.com/shytong/p/5351931.html
Copyright © 2020-2023  润新知