php
  • javascript
  • jquery
  • 2012-03-29 60 views 1 likes 
    1

    我在抓取由某些PHP代碼生成的頭標記內的實際文本時遇到問題。這是我抓住的頁面部分。抓取PHP生成元素中包含的文本

    <div class="container"> 
        <div class="majorContainer"> 
        <h2>Your results for: <small>"tables"</small></h2> 
        <hr /> 
        <div class='accordionButton'> 
         <h3 style="display:inline">1. </h3> 
         <h3 style="display:inline" id='major-1'>Electrical Engineering Technology</h3> 
         <p>...</p> 
        </div> 
        <div class='accordionButton'> 
         <h3 style="display:inline">2. </h3> 
         <h3 style="display:inline" id='major-2'>Retail Management</h3> 
         <p>...</p> 
        </div> 
    

    基本上,當用戶點擊「accordionButton」,我想拉從特定按鈕的標題標籤的文本。在我的PHP,我分配一個ID給每個標題標籤,因爲我想我可能只是拉文這樣做的:

    document.getElementById(this.getElementsByTagName("h3")[0].id).text 
    

    當我提醒在一個消息框,我只能看見「未定義」。我嘗試,而不是隻做...

    $(this).text() 
    

    ...但這返回「1.電氣工程技術...」,這是不是我想要的。我只想要標題爲「電氣工程技術」的標籤。

    我在做什麼錯?謝謝!

    回答

    1

    這會有幫助嗎?我正在使用jQuery 1.7.1。

    $(".accordionButton").on("click", function(){ 
        alert($(this).find("h3").eq(1).text()); 
    }); 
    

    如果您需要了解更多關於jQuery的,這裏是一個很好的鏈接,開始與http://tutsplus.com/course/30-days-to-learn-jquery/

    +0

    完美!非常感謝!但是,你能簡單地解釋一下這是如何工作的,僅僅是爲了我自己的理解? – Jon 2012-03-29 18:27:57

    +0

    當你點擊類「.accordionButton」的元素時,jquery搜索或找到第二個h3(eq(1)作爲索引從0開始)。 – DG3 2012-03-29 18:32:00

    +0

    明白了!感謝:D – Jon 2012-03-29 18:33:37

    1
    $(this).find("h3:last").text(); 
    

    由於DG3指出,你不能僅僅通過ID選擇 - 我被忽略原始請求。我已經修改了這個答案以反映實際的解決方案。

    +0

    你只是不能使用ID。 「accordionButton」類有多個元素,而id爲「major-1」的h3只與第一個手風琴有關。 – DG3 2012-03-29 18:38:28

    1
    $('.accordionButton').click(function(){ 
        alert($(this).find('h3:last').text()) 
    }); 
    

    演示:http://jsfiddle.net/Mq4JS/

    +0

    這也適用,所以我給你們一些upvotes。 – Jon 2012-03-29 18:32:34

    相關問題