jquery的val要领。

因子

或许你不知道(最少我之前是不知道的T_T),在jqueryval()要领中是能够直接写函数的。
比方

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>test</title>
    </head>
    <body>
        <form class="" action="index.html" method="post">
            <input type="hidden" id="test_input" name="name" value="">
        </form>
<script src="http://libs.useso.com/js/jquery/1.9.1/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript">
function test_callback(){
    return "hahaha";
}
var $obj=$("#test_input");
$obj.val(test_callback);
alert($obj.val());
</script>
    </body>
</html>

又比方

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>test</title>
    </head>
    <body>
        <form class="" action="index.html" method="post">
            <input type="hidden" id="test_input" name="name" value="">
        </form>
<script src="http://libs.useso.com/js/jquery/1.9.1/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript">
var $obj=$("#test_input");
$obj.val(function(){
    return "4444";
});
alert($obj.val());
</script>
    </body>
</html>

启事

为究其原因,我本日去jquery源码看了下,上面是这么写的:

//略去无关代码
isFunction = jQuery.isFunction( value );

return this.each( function( i ) {
    var val;

    if ( this.nodeType !== 1 ) {
        return;
    }

    if ( isFunction ) {
        val = value.call( this, i, jQuery( this ).val() );
    } else {
        val = value;
    }
    //略去无关代码
}

好啦,又涨新姿态了吧。。

能够看到显现推断是不是是一个函数,假如要设置的值是个函数,就会先实行他,然后把它的效果放到值内里返回。

    原文作者:rozbo
    原文地址: https://segmentfault.com/a/1190000005658158
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞