[英]Returning the value of an attribute using jquery
<script>
$(document).ready(function () {
$("#target").click(function () {
alert($(this).attr("width"));
});
});
</script>
<style>
#target {
height:300px;
width:300px;
background-color:#0094ff;
}
</style>
<body>
<div id="target"></div>
</body>
I am trying to return the attribute value of an html element.(Here: width(attribute) of the target(html element)). 我试图返回html元素的属性值。(这里:target(html元素)的width(attribute))。 But it alerts "undefined" for me.
但是它为我警告“未定义”。
Do you have any idea why? 你知道为什么吗?
$("#target").click(function () {
alert($(this).css("width"));
});
$("#target").click(function () {
alert($('#target').width()); //300: always returns integer as px unit
alert($('#target').css('width')); //300px: return width with string with suffix "px"
});
You are not asking to get the css height property, instead you are trying to get the attribute of your div. 您不是要获取css height属性,而是要获取div的属性。 Instead you should try with
.css(prop)
method: 相反,您应该尝试使用
.css(prop)
方法:
$(document).ready(function () {
$("#target").click(function () {
alert($(this).css("width"));
});
});
Your question: 你的问题:
But it alerts "undefined" for me. 但是它为我警告“未定义”。 Do u have any idea why?!!
你知道为什么吗?!
As i have written above you were trying to get the attribute of your div like (which in your case is not there.) : 正如我上面所写的,您正在尝试获取div的属性(在您的情况下不存在) :
<div id="target" width='500'></div>
<!---------------^^^this^^^-->
That is attribute width of your #target
div. 这就是
#target
div的属性宽度。 That is the main cause of alerting undefined
. 这是发出
undefined
警报的主要原因。
you are setting width property of css not an html attribute (also for your information , html attribute "width" is deprecated) to access the css property width use : 您要设置css的width属性而不是html属性(同样,供您参考,不建议使用html属性“ width”)来访问css属性width,请使用:
$("#target").click(function () {
alert($(this).css("width"));
});
try this may this will help you 试试这个可能对你有帮助
$(document).ready(function () {
$("#target").click(function () {
$(this).setAttribute("width", "480");
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.