jQuery按父元素的类获取span值

时间:2017-04-21 12:54:21

标签: javascript jquery

我需要通过父元素的类获得<span>值,我认为我做得很好,但它总是让我undefined ...我做错了什么? <a>有一个类,里面的链接是<span>,我需要得到这个值。代码如下,谢谢!

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>

2 个答案:

答案 0 :(得分:1)

由于您没有语法错误,因此加载了Jquery。

我能想到的唯一问题是你的文件尚未准备就绪。添加它

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

答案 1 :(得分:0)

.html()工作......请查看JSFIĐLE:https://jsfiddle.net/pn60L93q/1/

var currentConstructionName = $('a.chosen-single span').html();
console.log(currentConstructionName);
相关问题