Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery:AddClass_Jquery_Css - Fatal编程技术网

jQuery:AddClass

jQuery:AddClass,jquery,css,Jquery,Css,我有一个列表,其中span包含一个数字。我想将这个数字“复制”到它旁边跨度上的样式(将宽度设置为数字的百分比) HTML <span class="celebName">Per</span> <span class="celebPct">32</span> <span class="celebBar"></span> 我希望结果是这样的: <span class="celebName">Per</span

我有一个列表,其中span包含一个数字。我想将这个数字“复制”到它旁边跨度上的样式(将宽度设置为数字的百分比)

HTML

<span class="celebName">Per</span>
<span class="celebPct">32</span>
<span class="celebBar"></span>
我希望结果是这样的:

<span class="celebName">Per</span>
<span class="celebPct">32</span>
<span class="celebBar" style="width:32%;"></span>
Per
32
为什么这不起作用???

试试这个:

$('.celebPct').each(function(index) {
    var celebPct = $(this).text();
    $(this).next(".celebBar").css({"width":  celebPct+"%"});
});
这是一把小提琴:


另外,如果您只有一个css更改,那么在
.css
调用中不需要对象,您可以执行以下操作:
.css(“width”,celebPct+“%”)

跨度没有值,请尝试文本:

var celebPct = $(this).text();
您不能在span上使用
val()
,您需要使用
text()
。此外,css选项的语法也是错误的。可以在不使用对象的情况下设置一个选项。加上
text()
的返回值是一个字符串值,而不是jQuery,因此在连接时不需要用jQuery包装它

$('.celebPct').each(function(index) {
    var celebPct = $(this).text();
    $(this).next(".celebBar").css( "width", celebPct+"%" );
});
  • 使用
    text()
    而不是
    val()
    获取div的内部文本。val用于输入
  • 无需将结果
    celebPct
    包装到jquery中
  • 在传递到css的哈希中有一些语法错误
清理:

$('.celebPct').each(function(index) {
   var celebPct = $(this).text();
   $(this).next(".celebBar").css({"width": celebPct+"%"});
});

这似乎是错误的:

var celebPct = $(this).val();
使用

相反,因为span没有.val,只有输入/选择才有它

所以这应该是代码:

$('.celebPct').each(function(index) {
    var celebPct = $(this).html();
    $(this).next(".celebBar").css({"width": celebPct + "%";});
});
不需要使用$(celebPct),因为celebPct不是jquery元素

$(this).html()
$('.celebPct').each(function(index) {
    var celebPct = $(this).html();
    $(this).next(".celebBar").css({"width": celebPct + "%";});
});