0

好吧,标题可能根本没有任何意义。但无论如何,我会放一些简单的代码来澄清它。

我正在使用 JQuery 1.3.2

这是我的 JS

$(document).ready(function() {
  $('#test').click(function() {
    $('#result').html('<a href="#" id="hello">hello world</a>');
  });

  $('#hello').click(function() {
    $('#result').html('<a href="#" id="asdf">Test #2</a>');
  });
});

在 html 中,我有一个超链接 id='test' 和一个 id='result' 的 div。我期望这个 JS 代码是当我点击测试时,它会显示“Hello World”。之后,当我单击“Hello World”时,它应该显示“Test #2”

任何建议都非常有帮助...

谢谢你。

4

3 回答 3

8

正如 hobodave 所说,这与 Ajax 无关。

问题是 click() 函数在加载文档时附加到 HTML (在 DOM 就绪上)。但是,此时 Hello world div 还不存在。创建时,它没有点击事件。

您需要在添加新 div 时添加 click(),或者使用该 live()函数附加事件处理程序。

$(document).ready(function() {
  $('#test').live('click',function() {
    $('#result').html('<a href="#" id="hello">hello world</a>');
  });

  $('#hello').live('click',function() {
    $('#result').html('<a href="#" id="asdf">Test #2</a>');
  });
});

也就是说,对于您想要的功能,一种更简单的方法是在两个已经存在的 div 上使用hide()和。show()

于 2009-07-26T22:05:45.083 回答
2

首先,您的问题与 AJAX 无关。这是纯 JavaScript。您在上面定义的 onClick 侦听器绑定到页面加载时的适当元素(特别是 DOM Ready 事件)。当页面加载时,没有 id="hello" 的元素,因此它不会让监听器绑定到它。

您需要做的是将 id="hello" 的侦听器绑定嵌套在 id="result" 的点击事件中

例如

$(document).ready(function() {
  $('#test').click(function() {
    $('#result').html('<a href="#" id="hello">hello world</a>');
    $('#hello').click(function() {
      $('#result').html('<a href="#" id="asdf">Test #2</a>');
    });
  });
});
于 2009-07-26T22:05:51.683 回答
0

这是因为您在文档就绪中设置的元素的单击事件处理程序id="hello"不会绑定到该元素,因为在单击该元素之前它不存在于 DOM 中id="test"

解决此问题的一种方法是使用事件委托和live()命令。

另一种方法是在将元素添加到 DOM 的同时定义 click 事件处理程序。以下将在这种情况下正常工作

$(function() {
  $('#test').click(function() {
    $('#result')
        .html('<a href="#" id="hello">hello world</a>');
        $('#hello').click(function() {
            $('#result').html('<a href="#" id="asdf">Test #2</a>');
            // to prevent event propagation
            return false;
        });
    // to prevent event propagation
    return false;    
    });      
});

有用于将元素附加到其他元素的特定 jQuery 命令,在这种情况下可以很好地工作的命令是append()appendTo()。这是一个使用示例appendTo()

$(function() {
  $('#test').click(function() {

    $('<a href="#" id="hello">hello world</a>')
        .click(function() {
            $(this).replaceWith('<a href="#" id="asdf">Test #2</a>')
        })
        .appendTo('#result');
    });
});
于 2009-07-26T22:42:28.287 回答