iT邦幫忙

0

jquery 的 addClass 無法作用?

$(function () {
    let locationPath = location.pathname
    if (locationPath.indexOf(faqRenderURL) !== -1) { // output 0
        $('.faq-nav').addClass('onasd')
        console.log('in')
    }
})

確實有印出 in 但卻沒有執行 addClass
我直接在谷歌瀏覽器直接下 $('.faq-nav').addClass('onasd') 完全可以沒問題

https://imgur.com/jcwlHJj
https://imgur.com/jQrimjg

不曉得是為什麼?
還是說一定要有個事件才行? click ?
(都有清CACHE)

柯柯 iT邦新手 3 級 ‧ 2020-10-20 16:48:13 檢舉
faq-nav 是在一開始就有的class 還是載入網頁完成後才動態創建出來的class
火爆浪子 iT邦研究生 1 級 ‧ 2020-10-20 17:00:11 檢舉
確實,faq-nav 是 onload 後才創建的!
柯柯 iT邦新手 3 級 ‧ 2020-10-20 17:06:47 檢舉
那就是先onload 創建完faq-nav 在去跑 判斷加class

$( document ).ready(function() {
$('body').append('<div class="faq-nav"></div>');

let locationPath = location.pathname
if (locationPath.indexOf(faqRenderURL) !== -1) { // output 0
$('.faq-nav').addClass('onasd')
console.log('in')
}

});
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
邦吉安德森
iT邦新手 5 級 ‧ 2020-10-20 16:59:09
最佳解答

有種可能是,在執行 $('.faq-nav').addClass('onasd') 時,$('.faq-nav')這個DOM還沒有生成出來,可以在 $('.faq-nav').addClass('onasd') 段落console出$('.faq-nav')看看有沒有東西。

火爆浪子 iT邦研究生 1 級 ‧ 2020-10-20 17:00:45 檢舉

確實,faq-nav 是 onload 後才創建的!

火爆浪子 iT邦研究生 1 級 ‧ 2020-10-20 17:05:53 檢舉

請問在什麼情況下才需要用到 $(function () {

wolfwang iT邦研究生 4 級 ‧ 2020-10-21 12:33:40 檢舉

$( document ).ready(function() {}) 和 $(function(){}) 是一樣的意思

jQuery 程式最好都是包在 $(function(){}) 裡面執行,以免document 還沒載入完畢就執行,就會出現問題。

我要發表回答

立即登入回答