2016-11-24 102 views
2

我想將h4標籤中的文本更改爲其祖父div的類名(即sds 2016 gwap)。jquery selector在div下選擇h4標籤

<div class="grid"> 
     <div class="office-year-function sds 2016 gwap"> 
      <div class="content cell-child"> 
       <img src="535/img/01.jpg" alt="" width="312px" height="160px"> 
      </div> 
      <div class="img-hover cell-child"> 
       <br/> 
       <h3>GWAP Kick-off Ceremony</h3> 
       <h3>2016</h3> 
       <h4></h4> 

當文檔加載完成後,它會運行下面的函數。

function changeTag() { 
    for (var i = 1; i <= $('.office-year-function').length; i++) { 
     $this = $('div.grid div.office-year-function:nth-child(' + i + ')'); 
     var className = $this.attr('class'); 
     className = className.split(" "); 

     for (var j = 1; j < className.length; j++) { 
      className[j] = className[j].replace("-", " "); 

      if (className[j] == "gwap") { 
       $this.find("h4").html += className[j].toUpperCase(); 
      } else { 
       $this.find('h4').html += className[i].capitalize(); 
      } 
     } 
    } 

} 

$this.find("h4").html+=className[j].toUpperCase(); 
$this.find('h4').html+=className[i].capitalize(); 

這有什麼錯我的代碼有錯誤?

+0

'html()'是一個函數,你被視爲屬性。使用它像'$ this.find(「h4」)。append(className [j] .toUpperCase());' – Satpal

+0

'.html'是一個函數。將它用作'.html(content + classname)' –

回答

1

您當前的實施不起作用.html()是一個函數,您將其視爲屬性。您可以使用[0]來獲取底層DOM元素和使用innerHTML屬性。

$this.find("h4")[0].innerHTML +=className[j].toUpperCase(); 

但是,使用.append()可用於獲得所需的結果。

function changeTag() { 
    for (var i = 1; i <= $('.office-year-function').length; i++) { 
     $this = $('div.grid div.office-year-function:nth-child(' + i + ')'); 
     for (var j = 1; j < className.length; j++) { 
      className[j] = className[j].replace("-", " "); 
      if (className[j] == "gwap") { 
       $this.find("h4").append(className[j].toUpperCase()); 
      } else { 
       $this.find("h4").append(className[i].capitalize()); 
      } 
     } 
    } 
} 
0

我建議使用jQuery的.text(文本)而不是.append()作爲跟隨,選擇是你的。

function changeTag() { 
    for (var i = 1; i <= $('.office-year-function').length; i++) { 
     $this = $('div.grid div.office-year-function:nth-child(' + i + ')'); 
     for (var j = 1; j < className.length; j++) { 
      className[j] = className[j].replace("-", " "); 
      if (className[j] == "gwap") { 
       $this.find("h4").text(className[j].toUpperCase()); 
      } else { 
       $this.find("h4").text(className[i].capitalize()); 
      } 
     } 
    } 
} 

按照文檔:http://api.jquery.com/append/

.append()當你正在處理DOM元素被使用。

根據您當前的需求,您只需要將h4標籤的內容更新爲祖父母公司的分類名稱即可。

所以,文本(文本)就足夠了。

將匹配元素集合中每個元素的內容設置爲 指定的文本。