繁体   English   中英

尝试使用javascript使用类属性在html标记中打印值

[英]trying to print the value in a html tag with a class attribute using javascript

如果html中的内容不为空,我尝试使用其css值在html标记中打印内容。 这是javascript代码块中的代码段

<script>

    jQuery(document).ready(function(){

    function myFunction() {
    var x = document.getElementsByClassName("simpleproduct");
    if(x != null){
    var y = x[0].innerHTML;
    alert(y);

    }
}

});
        </script>

这是调用javascript函数的按钮

<button onclick="myFunction()">ClickToSee</button>

这是具有css值的示例html标签

<h5 class="simpleproduct">199.99</h5>

请如何使用class属性在html标记中获取值。

 jQuery(document).ready(function() {}); function myFunction() { var x = document.getElementsByClassName("simpleproduct"); if (x != null) { var y = x[0].innerHTML; alert(y); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button onclick="myFunction()">ClickToSee</button> <h5 class="simpleproduct">199.99</h5> 

将函数放在jquery.ready之外

当您使用jQuery时,它是如此简单

 $(document).ready(function(){ $('#myButton').on('click', myFunction); function myFunction() { var text = $(".simpleproduct").text(); alert(text); } }); 
 <button id="myButton">ClickToSee</button> <h5 class="simpleproduct">199.99</h5> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

注意: simpleproduct选择器可以进一步完善,以基于完整的模板结构仅返回一个元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM