Javascript 想知道为什么这个jQuery没有';不行?
我拼凑了下面的jQuery来制作手风琴效果。这很有效Javascript 想知道为什么这个jQuery没有';不行?,javascript,jquery,html,jquery-ui,Javascript,Jquery,Html,Jquery Ui,我拼凑了下面的jQuery来制作手风琴效果。这很有效 $("#FAQs .answer").hide(); $("#FAQs .close").hide(); $("#FAQs .open").show(); // Click the #Expand button to show and hide .answer $('#Expand').click(function() { if ($(this).text() === 'Minimise FAQs') { $(this).text
$("#FAQs .answer").hide();
$("#FAQs .close").hide();
$("#FAQs .open").show();
// Click the #Expand button to show and hide .answer
$('#Expand').click(function() {
if ($(this).text() === 'Minimise FAQs') {
$(this).text('Expand FAQs');
$('#FAQs .answer').slideUp('fast');
$("#FAQs .close").hide();
$("#FAQs .open").show();
} else {
$(this).text('Minimise FAQs');
$('#FAQs .answer').slideDown('fast');
$("#FAQs .close").show();
$("#FAQs .open").hide();
}
});
// Click the Quesiton (h2) to show and hide the answer
$("#FAQs h2").addClass("link").click(function() {
$(this).parent().children(".answer").slideToggle('fast');
$(this).parent('li').children(".close").toggle();
$(this).parent('li').children(".open").toggle();
});
此代码(如上)使以下HTML打开和关闭页面上的所有手风琴:
<section class="row m_b_zero">
<div class="inner-container">
<div class="box">
<div class="box-inner"> <div class="faq-controls">
<span id="Expand">Expand FAQs</span>
</div></div>
</div>
</div>
</section>
展开常见问题解答
这仍然很有效
不过
我需要使用jQuery将HTML注入页面,所以我将其拼凑起来:
$(function() {
$( 'section:nth-child(2)' ).after( '<section class="row m_b_zero"><div class="inner- container"><div class="box"><div class="box-inner"><div class="faq-controls"><span id="Expand">Expand FAQs</span></div></div></div></div></section>' );
});
$(函数(){
$('section:nth child(2)')。在('Expand faq')之后;
});
这将在第二个
标记之后注入与之前相同的accordion控制器HTML
这几乎奏效了
HTML按预期注入,但按钮不起作用?它不能打开和关闭手风琴
我已经确保这个jQuery放在jQuery控制accordio之后,并且它位于一个页面就绪函数中
有人知道它为什么不起作用吗?您给两个不同的元素提供了相同的
id
。在jQuery中使用id选择器时,它只返回具有该id的第一个元素。您应该改用类:
//HTML
<span class="Expand">Expand FAQs</span>
//JS
$('.Expand').click(function() {
- 文档中的多个元素不能具有相同的id(无效)。您应该改用类名
- 您应该为动态添加的元素委派事件处理程序。假设您使用的是class
,则可以使用来委托事件处理程序,如下所示:Expand
$(document).on("click",".Expand", function() { // code });
文档
仅用于演示目的,最好使用最接近的静态祖先您需要使用$()。on()
将事件附加到动态添加的元素上以进行微调!明天早上我会看一看。谢谢,看来要走了。
$(document).on("click",".Expand", function() {
// code
});