jQuery读取值但返回空字符串

时间:2014-11-26 21:10:32

标签: javascript jquery html

所以我有函数读取文本输入的值,我只想console.log该值以确保它正常工作。但是console.log只返回空字符串。我的Chrome开发者工具没有显示错误。 这是代码:

<body>
   <input type="text" id="text-input" name="fname" placeholder="Last name">
   <button>Confirm</button>
</body>
<script>
    (function () {

        function searchFunction () {
            var stringValue = $('#text-input').val();
            $('button').on('click', function () {
                console.log(stringValue);
            });
        }

        searchFunction ();

    })();
</script>

1 个答案:

答案 0 :(得分:4)

当然它确实......你在运行时设置stringValue的值 - 当值为空时,你永远不会在点击事件中重新获取它:

function searchFunction () {
    var stringValue = $('#text-input').val();

    $('button').on('click', function () {
        stringValue = $('#text-input').val(); //RESET THE VARIABLE TO THE CURRENT VALUE
        console.log(stringValue);
    });
}

searchFunction ();
相关问题