2017-04-21 66 views
0

我需要獲得<span>父類元素的值,我認爲我做得很好,但它總是拋出undefined ...我該做什麼錯誤? 有<a>其中有班級和裏面的鏈接是<span>,我需要得到的價值。代碼如下,謝謝!jQuery通過父元素的類獲得範圍值

FIDDLE:https://jsfiddle.net/pn60L93q/

<a class="chosen-single" tabindex="-1"> 
     <span> 
      I/37 Chrudim - obchvat, úsek křiž. I/17 - Slatiňany 
     </span> 
    </a> 

<script> 
    var currentConstructionName = $('a.chosen-single span').text(); 
    console.log(currentConstructionName); 
</script> 
+1

你做你的代碼之前添加jQuery庫? –

+0

**。html()**請 – HoangHieu

+0

您的代碼中還有其他事情正在進行 - 如果我將它複製到jQuery中的代碼段中並添加了控制檯日誌「I/37 Chrudim - obchvat,úsekkřiž。I/17 - Slatiňany 「如預期。 –

回答

1

既然你有沒有語法錯誤,你的jQuery的加載。

唯一的問題,我能想到的是你的文件沒有準備好。它添加

$(document).ready(function(){ 
    var currentConstructionName = $('a.chosen-single span').text(); 
    console.log(currentConstructionName); 
    }) 
+0

現在我只得到空的日誌... – HS1993

+0

@ HS1993你能用你的代碼做一個小提琴嗎? –

+0

它已在問題 – HS1993

0

的.html()任職...請檢查JSFIĐLE:https://jsfiddle.net/pn60L93q/1/

var currentConstructionName = $('a.chosen-single span').html(); 
console.log(currentConstructionName); 
相關問題