首頁  >  問答  >  主體

使用JQuery僅在段落中出現特定字元時觸發點擊事件

我有一個手風琴,其中一些文字標記為“重要”。我希望頁面透過點擊頁面載入時的按鈕切換來自動開啟標記為「重要」的頁面。

我已經使用$(".diff__filename:contains('sections/')")) 在標題中搜尋「重要」一詞,但我不知道如何告訴它點擊旁邊的按鈕。

我選擇使用 JQuery 以避免循環遍歷類別名稱。

<p class="title">
  Important: Content 1
  <button class="toggle">Open</button>
</p>
<p class="title">
  Content 2
  <button class="toggle">Open</button>
</p>
<p class="title">
  Content 3
  <button class="toggle">Open</button>
</p>
<p class="title">
  Important: Content 4
  <button class="toggle">Open</button>
</p>

P粉269530053P粉269530053244 天前439

全部回覆(1)我來回復

  • P粉717595985

    P粉7175959852024-02-18 09:15:59

    您可以在元素上使用 :contains,然後觸發點擊:

    $('document').ready(function() {
    
      $('button').click(function() {
        let name = $(this).data('name');
        console.log('click on:', name);
      });
    
      $('div p:contains("Important")').find('button').trigger('click');
    
    });
    sssccc
    

    Important: Content 1

    Content 2

    Content 3

    Important: Content 4

    負載輸出:

    click on: Button 1
    click on: Button 4

    回覆
    0
  • 取消回覆