簡體   English   中英

在Javascript中獲取HTML 5圈的屬性

[英]Get Attributes of HTML 5 Circles in Javascript

我有多個html圈子使用D3.js附加到svg 每個圓圈都沒有任何ID或類,當我檢查瀏覽器中的元素時看起來像:

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

我想將cxcy的值變為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');方法設置的值.data $('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 Object。 於是

 $('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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM