jQuery单击函数和回调数组

jQuery单击函数和回调数组

问题描述:

I`m new to jQuery and have a problem understanding functions.

I have the following structure of HTML code:

<ul class="result">
   <li id="a"></li>
   <li></li> //will be added through a loop depending on input
</ul>

And this jQuery code:

$(document).ready(function() { //changes are possible when the page has fully loaded
    $('.inp').keyup(function() { //executes keyup function to the field class "inp"
        var inp = $(this).attr('value'); //sets a variable with the value of input from class="inp"
        $.post('ajax/file.php', {inp:inp}, function(data) { //posts that value to file.php as variable inp and executes the function (data) to this 
            $('.result').html(data);  //adds the returned result into HTML content as a first element in the set of class="result" => <li>

            $('.result li').click(function() { //executes click function when clicking li element
                var result_value = $(this).text(); //sets a variable and prepares something as text 
                $('.inp').attr('value', result_value); //fills value attribute of field class "inp" with the variable result_value
                $('.result').html(''); //???
            });
        });
    });
});

Now my question is what $('.result').html(''); does?

JQuery .html() property sets the html of the object it is mapped to, it have same behavior like the javascript property .innerHTML.

So here in your scenario $('.result').html(''); will set the html of result class element to null.

<ul class="result">
</ul>

Secondly, you are using wrong approach in your 'file.php', instead use this code:

echo '<li>'.$row["name_1"].'</li>';
echo '<li>'.$row["name_2"].'</li>';
echo '<li>'.$row["name_3"].'</li>';

$('.result').html(''); sets the html of .result to a blank string.

$('.result').html(''); clears the contents of <ul class="result">.

http://api.jquery.com/html/