0

小问题。我有一些 JavaScript,当我点击一个功能块时,它会改变一些 div 的内容。从我下面的代码中可以看出,#pubcontent 是添加到页面的一些链接。

$("#publications").click(function(){
    $("#content").html('<iframe id="idIframe" src="publication/index.html" style="height:594px;width:98%;"></iframe>');
    $("#titlepage").html('<img src="../images/pageline.png" style="width:2px; height:50px; vertical-align:middle"/>Home&nbsp;&nbsp;>&nbsp;&nbsp;Publications');
    $("#researchcontent").html('');
    $("#pubcontent").html('<ul><li><a id="2013" href="#">2013</a></li><li><a id="2012" href="#">2012</a></li><li><a id="2011" href="#">2011</a></li><li><a id="2010" href="#">2010</a></li><li><a id="2009" href="#">2009</a></li><li><a id="2008" href="#">2008</a></li></ul>');
});

这是有效的。但是现在,我在同一个 JavaScript 文件中有一些其他代码,当我单击属于 #pubcontent 的链接时应该执行这些代码。但是当我点击链接时,什么也没有发生。这段代码是:

$("#2013").click(function(){
    $("#content").html('<iframe id="idIframe" src="publication/index.html#2013" style="height:594px;width:98%;"></iframe>');
    $("#titlepage").html('<img src="../images/pageline.png" style="width:2px; height:50px; vertical-align:middle"/>Home&nbsp;&nbsp;>&nbsp;&nbsp;Publications&nbsp;&nbsp;>&nbsp;&nbsp;2013');

所以总结一下。我按下 x 并显示 y。如果我按下 y 中的链接,我想看到 z。但我找不到让“z”部分出现的方法。我不确定这个解释是否有帮助..但是有人建议吗?

4

2 回答 2

3

对动态添加的元素使用委托:

$("#pubcontent").on('click',"#2013",function(){...});

当然,上下文页面中的 ID 必须是唯一的,因此 ID 为“2013”​​的元素应该是唯一的。

于 2013-07-03T08:08:02.560 回答
0

您应该将第二个代码块放在 $("#publications").click(...) 函数中,就在最后一行之后。

您无法在页面加载时对其进行初始化。jQuery 不会听 $("#2013") 因为它在那一刻不存在。

尝试这个:

$("#publications").click(function(){
    $("#content").html('<iframe id="idIframe" src="publication/index.html" style="height:594px;width:98%;"></iframe>');
    $("#titlepage").html('<img src="../images/pageline.png" style="width:2px; height:50px; vertical-align:middle"/>Home&nbsp;&nbsp;>&nbsp;&nbsp;Publications');
    $("#researchcontent").html('');
    $("#pubcontent").html('<ul><li><a id="2013" href="#">2013</a></li><li><a id="2012" href="#">2012</a></li><li><a id="2011" href="#">2011</a></li><li><a id="2010" href="#">2010</a></li><li><a id="2009" href="#">2009</a></li><li><a id="2008" href="#">2008</a></li></ul>');
    $("#2013").click(function(){
        $("#content").html('<iframe id="idIframe" src="publication/index.html#2013" style="height:594px;width:98%;"></iframe>');
        $("#titlepage").html('<img src="../images/pageline.png" style="width:2px; height:50px; vertical-align:middle"/>Home&nbsp;&nbsp;>&nbsp;&nbsp;Publications&nbsp;&nbsp;>&nbsp;&nbsp;2013');
    });
});
于 2013-07-03T08:07:42.527 回答