开发者

jQuery selecting list items

开发者 https://www.devze.com 2023-03-03 17:52 出处:网络
I\'m having trouble seeing what\'s wrong with my code. I\'m trying to select my list items, but they don\'t seem to get selected.

I'm having trouble seeing what's wrong with my code. I'm trying to select my list items, but they don't seem to get selected.

Here's my HTML

    <!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Tasklistr</title>
    <style type="text/css"> @import url(styles.css);</style>
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js'></script>
    <script type="text/javascript" src="application.js"></script>
</head>

<body>
  <h1>JSTasker</h1>

  <form>
    <fieldset>
      <legend>Add a Task</legend>
      <input type='text' name='task_text' id='task_text' />
      <input type='submit' name='add_button' value='Add' id='add_button' />
    </fieldset>
  </form>

  <div id='tasks'>
      <h2>Your Tasks </h2>
      <ul>
      </ul>
  </div>
</body>
</html>

My application.js

$(document).ready(function() {
    $('input#add_button').click(function(event) {
        event.preventDefault();
        var task_text = $('input#tas开发者_Python百科k_text').val();
        var task_item = "<li><p>" + task_text + "</p></li>"
        $('div#tasks ul').append(task_item);
        $('input#task_text').val(null);
    });

    $('input#task_text').focus();

    $('div#tasks ul li').click(function() {
        alert("Hey");
    });



});


You should use .live() instead of .click().

You are currently binding a click event to DOM-elements that don't exist at the time of binding (since you are adding them by clicking the button). live() solves this problem: events bound by this method also work for elements that are created after live() is called.

Example:

$('div#tasks ul li').live('click', function(){
    alert("Hey");
});
0

精彩评论

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