开发者

jquery call function by name

i have function

<script type="text/javascript">
    $(function () {
        $("#search").click(fun开发者_Go百科ction() {
            var text = $("#searchText").val();
            $.getJSON("Search", { world: text, filter: text }, function(data) {
                $("tr.DataRow").toggle(false);
                for (i = 0; i < data.length; i++) {
                    $("#obj" + data[i]).toggle(true);
                }
            });
        })            
    });


</script>

now i have another function

<script type="text/javascript">

    $(function() {
        $('#searchText').bind('keypress', function(e) {
            if (e.keyCode == 13) {

            }
        });
    });
</script>

how can i call first function from second function?


You can raise a click event on the element you registered the first function

<script type="text/javascript">

    $(function() {
        $('#searchText').bind('keypress', function(e) {
            if (e.keyCode == 13) {
                $('#search').click(); // Raise a click event on #search element
            }
        });
    });
</script>


Extract the logic from the first event handler into a named function:

function doSearch() {
    var text = $("#searchText").val();
    $.getJSON("Search", { world: text, filter: text }, function(data) {
        $("tr.DataRow").toggle(false);
        for (i = 0; i < data.length; i++) {
            $("#obj" + data[i]).toggle(true);
        }
    });
}

You can now pass doSearch by name to the click handler:

    $(function () {
        $("#search").click(doSearch);
    });

and explicitly invoke it from within the key handler:

    $(function () {
        $('#searchText').bind('keypress', function(e) {
            if (e.keyCode == 13) {
                doSearch();
            }
        });
    });


// first function
$(function() {
  $.yourFavoriteFunctionName = function() {
    // the code for the first function
  };
  $.yourFavoriteFunctionName();
});

then

// second function
$(function() {
  // whatever
  if (foo)
    $.yourFavoriteFunctionName();


you could give it a name? am I missing something?

edit: to get this right

<script type="text/javascript">
function() myfunction{
    var text = $("#searchText").val();
    $.getJSON("Search", { world: text, filter: text }, function(data) {
        $("tr.DataRow").toggle(false);
        for (i = 0; i < data.length; i++) {
            $("#obj" + data[i]).toggle(true);
        }
    });
}

$(function(){
    $("#search").click(myfunction);
});
</script>

and then

<script type="text/javascript">

$(function() {
    $('#searchText').bind('keypress', function(e) {
        if (e.keyCode == 13) {
            myfunction();
        }
    });
});
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜