从URL触发点击事件

时间:2014-05-05 00:26:35

标签: jquery

我正在构建一个FAQ页面,我需要帮助我的jquery函数的第二部分。 当您单击某个问题时,它会显示答案。 我还想做的是当我链接到锚点时,也显示问题的答案。

脚本:

jQuery(function($) {
    $('.faq-title').click(function () {
        $(this).siblings('.faq-content').slideToggle('fast');
    })
var hash = window.location.hash;
    $('.faq-title').find('a[href*='+ hash + ']').closest('h4').trigger('click');
})

HTML

<div class="faq">
    <h4 class="faq-title" style="cursor:pointer;padding:0 0 6px 0;"><a id="q1"></a>1. <span style="text-decoration:underline;">Question</span></h4>
    <div class="faq-content" style="display:none;"><p style="color: #808080;">Answer</p></div>
</div>
<div class="faq">
    <h4 class="faq-title" style="cursor:pointer;padding:0 0 6px 0;"><a id="q2"></a>2. <span style="text-decoration:underline;">Question</span></h4>
    <div class="faq-content" style="display:none;"><p style="color: #808080;">Answer</p></div>
</div>
<div class="faq">
    <h4 class="faq-title" style="cursor:pointer;padding:0 0 6px 0;"><a id="q3"></a>3. <span style="text-decoration:underline;">Question</span></h4>
    <div class="faq-content" style="display:none;"><p style="color: #808080;">Answer</p></div>
</div>

2 个答案:

答案 0 :(得分:1)

更改您的javascript:

.find(hash)

检查fiddle

答案 1 :(得分:0)

我添加了CSS来清理HTML。基本上,只需检查是否存在哈希(例如,#q3),如果存在,则触发附加到其上的事件处理程序。在这种情况下,请点击#q3

fiddle

<强> HTML:

<div class="faq">
    <h4 class="faq-title">
        <a id="q1"></a>1. <span>Question</span>
    </h4>
    <div class="faq-content">
        <p>Answer</p>
    </div>
</div>
<div class="faq">
    <h4 class="faq-title">
        <a id="q1"></a>2. <span>Question</span>
    </h4>
    <div class="faq-content">
        <p>Answer</p>
    </div>
</div>
<div class="faq">
    <h4 class="faq-title">
        <a id="q1"></a>3. <span>Question</span>
    </h4>
    <div class="faq-content">
        <p>Answer</p>
    </div>
</div>

<强> CSS:

h4.faq-title {
    cursor: points;
    padding: 0 0 6px 0;
}
span {
    text-decoration: underline;
}
p {
    color: #808080;
}
div.faq-content {
    display: none;
}

<强> JavaScript的:

jQuery(function ($) {
    var hash = window.location.hash;
    if (hash) {
        $(hash).closest("h4").trigger("click");
    }
    $('.faq-title').click(function () {
        $(this).siblings('.faq-content').slideToggle('fast');
    })
})
相关问题