3
  <script type="text/ecmascript">
  <![CDATA[
  function setCoordinates(circle) {
  var centerX = Math.round(Math.random() * 1000);
  var centerY = Math.round(Math.random() * 1000);      
  circle.setAttribute("cx",centerX);
  circle.setAttribute("cy",centerY);
  }
  ]]>
  </script>


  <circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
  <circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
  <circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
  <circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
  <circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />


  <script type="text/ecmascript">
  <![CDATA[
  setCoordinates(document.getElementsByClassName("circles"));
  ]]>
  </script>

这根本没有效果。但是,当我使用“getElementByID”并为圆圈分配一个 ID 时,它工作正常。(歌剧)

4

1 回答 1

6

document.getElementsByClassName返回元素的集合,因此您需要遍历结果:

var elements = document.getElementsByClassName('circles');

for (var i = 0; i < elements.length; i++) {
    var element = elements[i];

    setCoordinates(element);
}

如果您的代码不能正常工作,请检查您的 JS 控制台。您应该会看到类似Object has no method 'setAttribute'.

于 2013-01-19T13:53:25.707 回答