text方法中的javascript设置变量

javascript set variable from .text method

本文关键字:设置 变量 javascript 方法 text      更新时间:2024-07-04

我是javascript开发的新手,我想了解如何从text方法设置变量。

示例:在这个代码中有一个文本方法

        $('.phone').text(theRestaurant.phone);
        $('.location').text(theRestaurant.location);
        $('.info').text(theRestaurant.info);

在Html文件中,当我从中创建任何类时,都会打印JSON文件中的值。

示例:

        <div class='phone'></div>

输出:(000)000-9999

源代码:

        <div class='phone'>(000)000-9999</div>

我试图在变量中设置它,但它不起作用。

我的尝试:

        var phone = theRestaurant.phone

我想把它设置在变量中,因为我需要把它放在href值中,比如:

<script>
    var phone = 'tel:' + phone
    document.getElementById("phone").href = phone;
</script>

我希望一切都清楚。如果有其他解决方案,请告知。

感谢

您是否将jQuery代码包装在document.ready()包装器中?

如果没有,那么javascript可能会在页面有时间在DOM中创建元素之前运行,并且什么都不起作用。

<script>
$(document).ready(function(){
     //all javascript/jQuery code goes in here
});
</script>

另外,请参阅我上面关于混淆"ByClassName"answers"ByID"的评论

答案来自@itsgoingdown

主javascript文件中的这段代码:

var phone=document.getElementById('phone').innerHTML; document.getElementsByClassName("phone")[0].href = phone;