在 JavaScript 中获取 HTML 5 圆圈的属性

Get Attributes of HTML 5 Circles in Javascript

本文关键字:属性 HTML JavaScript 获取      更新时间:2023-09-26

>我有多个使用 D3 附加到svg的 html 圆圈.js。 每个圆圈都没有任何 ID 或类,当我检查浏览器中的元素时看起来:

<circle cx="50" cy="80" r="1" style="fill: rgb(255, 0, 0);"></circle>

我想将cx的值和cy获取到 javascript 变量中。

我尝试了类似的东西:

var v = $('circle').value;

但是如何引用属性cxcy

我试过var x_val = $('circle.cx').value;但那是不确定的。

也尝试了var x_val = $('circle').data('cx');但这是空的。

element.value;获取纯JavaScript对象的值,而不是jquery对象的值。

$('circle').data('cx') ; 获取属性data-cx=""的值或以前使用方法 $('circle').data('cx', 'whatever'); 设置的值

要获取cxcy值,请使用:

var x_val = $('circle').attr('cx');
var y_val = $('circle').attr('cy');

更新:

要迭代到多个圆圈:

var x_val, y_val;
$circleArray = $('circle'); //get all circles
$circleArray.each(function(idx, el){//go through each circle
  x_val = $(el).attr('cx');//get cx
  y_val = $(el).attr('cy');//get cy
  $('#result').append(idx+': '+x_val+' / '+y_val);//here: print the values, but replace this with whatever you need
});

http://jsfiddle.net/pu2cnLgk/1/

这很容易在不使用 JQuery 的情况下完成,特别是如果你的圈子有一个 id。

<circle id='awesomeCircle' cx="50" cy="80" r="1" style="fill: rgb(255, 0, 0);"></circle>

你的 JavaScript 代码是:

var x = document.getElementById('awesomeCircle').getAttribute('cx');
var y = document.getElementById('awesomeCircle').getAttribute('cy');

如果您不愿意为元素分配 id,您可以使用

var x = document.getElementsByTagName('circle')[0].getAttribute('cx');
var y = document.getElementsByTagName('awesomeCircle')[0].getAttribute('cy');

不过,这将对浏览器兼容性产生负面影响。

$('circle') 会给你 jQuery 对象。因此

 $('circle').value  //undefined

因为jQuery中没有值变量或方法。

由于有很多圈子,你可以这样做

$('circle').each(function(index,elem){
  
   alert("cx :"+elem.getAttribute("cx")+"...cy :"+elem.getAttribute("cy")); //using JavaScript
   console.log("cx :"+$(elem).attr("cx")+"...cy :"+$(elem).attr("cy")); // using jQuery
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<circle cy="10" cx="210"></circle>
<circle cy="30" cx="210"></circle>
<circle cy="20" cx="201"></circle>
<circle cy="10" cx="210"></circle>