jQuery .attr()为现有属性返回“undefined”

时间:2016-02-15 21:21:55

标签: javascript jquery html svg

我一直在尝试使用jQuery(v2.1.4)访问svg:rect DOM元素上定义的自定义属性。具体要素如下:

<rect id="lane2-diag_D" currentLane="2" class="draggableCircle" x="250" y="125" height="20" width="10" clr="Chartreuse" style="stroke: gray; stroke-width: 1px; fill: chartreuse;"></rect>

此元素是从另一个元素克隆的,并且它的id已更改。我在将该属性添加到页面上的svg元素后尝试访问该属性。

当我尝试使用currentLane访问$('#lane2-diag_D').attr('currentLane')属性时,它会返回undefined。如果我尝试使用javascript方法document.getElementById('lane2-diag_D').getAttribute('currentLane')访问它,则会返回正确的值。

对于所有其他元素属性,jQuery返回正确的值。

我在jQuery语法中缺少什么?

1 个答案:

答案 0 :(得分:0)

您应该将代码置于就绪功能中并且它将起作用,请查看下面的示例。

希望这有帮助。

&#13;
&#13;
$(function(){
  alert($('#lane2-diag_D').attr('currentLane'));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<rect id="lane2-diag_D" currentLane="2" class="draggableCircle" x="250" y="125" height="20" width="10" clr="Chartreuse" style="stroke: gray; stroke-width: 1px; fill: chartreuse;"></rect>
&#13;
&#13;
&#13;

相关问题