2017-02-16 50 views
0

我不想在我的svg中显示所有的白色填充路径。用jquery填充颜色选择Svg路径

想象这种结构的SVG:

<svg> 
    <path class="pathok"fill="rgb(29,233, 182)"/> 
    <path class="pathok" fill="rgb(255, 255, 255)" /> 
    <path class="pathok" fill="rgb(255, 255, 255)" /> 
    <path class="pathok" fill="rgb(255, 255, 255)"/> 
</svg> 

我试过这个,但不工作:

<script> 
    if ($("path").attr("fill") == ("rgb(255, 255, 255)")) { 
     $(this).css("display","none") 
    } 
</script> 

一般情况下,我怎么能由他的属性的值选择标签?

回答

1

您的选择器正在获取所有路径,而不是单个路径。

试试这个:

$(document).ready(function(){ 
    var $paths = $('path'); // Get all paths 
    for (var i=0;i<$paths.length;i++){ // Iterate through each one 
     var $path =$($paths[i]); // This gets a single path 
     if ($path.attr("fill") == ("rgb(255, 255, 255)")) { 
      $path.css("display","none"); 
     } 
    } 
}); 
+0

它的工作。我是js的初学者。你能向我解释变量i的用法吗?谢谢。 – vlk

+0

是的。 '我'被用作'索引'或'计数器'。我们需要一个计数器来跟踪我们在'for ...'循环中的位置,因为我们使用计数器来访问'$ paths'对象中的当前项(即$ paths [i])。每次for循环迭代(循环)'i'都会增加1(这是通过'i ++'完成的。希望有帮助。 – Chris

+0

为什么只要选择你想要的就迭代? –

0

您只需选择您想要直接,不需要回路的元素。

我已经使用了rect元素而不是路径,因为您没有提供和d属性,但原理是相同的。

$("rect[fill='rgb(255, 255, 255)']").css('display', "none");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<svg> 
 
    <rect width="90" height="30" fill="black"/> 
 
    <rect width="10" height="10" x="10" y="10" fill="rgb(29,233, 182)"/> 
 
    <rect width="10" height="10" x="30" y="10" fill="rgb(255, 255, 255)" /> 
 
    <rect width="10" height="10" x="50" y="10" fill="rgb(255, 255, 255)" /> 
 
    <rect width="10" height="10" x="70" y="10" fill="rgb(255, 255, 255)"/> 
 
</svg>