![](/img/trans.png)
[英]Javascript - Applying class to an HTML tag given an attribute/value
[英]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.