2
一些文字链接1
<a href="http://anotherlink.com">link2</a>

和jQuery代码:

$('#inner a').click(function(){
   console.log( 'achtung' );
});

但是当我点击link1时,点击处理程序不会调用。

在另一种情况下:

$('a').click(function(){
   console.log( 'achtung' );
});

当我点击link2时,处理程序调用,但link1仍然无法正常工作。

你能解释一下:为什么?


这是更多代码:

 <div id="text-wrapper">
    <div id="text">
       <div id="content_close">close</div>
       <div id="inner">
       <!--Here will be content--> <br />               
    </div>
    ...
 </div>

内容由 ajax 加载到内部块中。


我的问题在于我正在动态加载带有链接的内容,因此,当 jquery 代码运行时,页面可能无法满足我的链接。所以我必须使用实时功能:

$('#inner a').live( 'click', function(){ alert('achtung'); } );

谢谢大家,问题解决了。

4

5 回答 5

2

你的 jQuery 代码被包裹在里面了$(document).ready(function(){ ... })吗?

如果您没有等待 DOM 准备好,则 jQuery 可能无法找到#inner.

$(document).ready(function(){
    $('#inner a').click(function(){
        console.log( 'achtung' );
    });
});
于 2009-10-12T17:01:55.737 回答
1

当我改变

 console.log( 'achtung' );

 alert( 'achtung' );

它按预期对我有用。

也许你的控制台运行不正常,或者你用来查看它的任何东西都不能正常工作?


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
</head>
<body>
<div id="inner">some text <a href="#contacts">link1</a></div>
<p><a href="http://anotherlink.com">link2</a> <script type="text/javascript">
/*<![CDATA[*/
$('#inner a').click(function(){
   alert( 'achtung' );
});
/*]]>*/
</script></p>
</body>
</html>
于 2009-10-12T16:47:43.737 回答
0

有两种方法可以实现这一点。必须加载 HTML 或仅加载节点。为此,您必须在 DOM 完全更新后检查您的页面是否已加载或执行 JavaScript。

如果您<head>像这样指定您的javascript:

<script type="text/javascript">
  $('#inner a').click(function(){
    console.log( 'achtung' );
  });
</script>

它会在读取时执行。HTML 的其余部分未加载到 DOM 中,因此 JavaScript 无法找到“#inner a”元素。有几种方法可以检查您的页面是否已加载

// simplest form, not the best (without jQuery)
window.onload = function () {
  // search for the node with jQuery
  $('#inner a').click(function(){
    alert( 'achtung' );
  });
}

// jQuery form, best
$(document).ready(function () {
  // search for the node with jQuery
  $('#inner a').click(function(){
    alert( 'achtung' );
  });
});

// smallest jQuery from, also best
$(function () {
  // search for the node with jQuery
  $('#inner a').click(function(){
    alert( 'achtung' );
  });
});

另一种方法是在 domnode 之后放置内联 JavaScript

<div id="inner">
  <a href="/test.html">link1</a>
</div>
<a href="/test2.html">link2</a>`
<script type="text/javascript">
  /*<![CDATA[*/
  $('#inner a').click(function(){
    alert( 'achtung' );
  });
  /*]]>*/
</script>
于 2009-10-13T07:40:44.333 回答
0

您的innerID 在页面中是唯一的吗?

您可以尝试在 Firebug 中查询它document.getElementById("inner")并查看返回的 DOM 节点是否是您所期望的(将结果悬停在 Firebug 中,将突出显示页面中的 DOM 节点)。

于 2009-10-12T17:11:47.773 回答
0

只是一种预感,试着放一个“回报”;或“调试器”;作为函数的最后一行。我想知道点击链接是否会导致控制台被清除。

于 2009-10-12T17:04:40.707 回答