在 JavaScript 中获取 HTML 5 圆圈的属性
Get Attributes of HTML 5 Circles in Javascript
>我有多个使用 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;
但是如何引用属性cx
和cy
?
我试过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');
设置的值
要获取cx
和cy
值,请使用:
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>
相关文章:
- 分析高度属性时出现意外值{{specs.height}}.index.html
- 获取HTML属性中CSS声明的值
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- HTML范围:动态设置值属性
- 如何通过HTML+CSS中的另一个元素Selector更改元素的属性值
- 一个正则表达式,用于从JS中的HTML标记中删除id、样式和类属性
- 自定义HTML元素属性未显示-Web组件
- 如何在CSS或Javascript中定位选定的属性(在HTML选项中)
- 函数jquery.html()不提供数据属性集值
- Android在HTML容器中滚动,该容器具有CSS溢出属性
- 如何使用Undercore和Backbone在HTML中表示模型属性
- Regex剥离具有特定属性的html标记
- html5中数据描述属性中的html列表
- 不存在的属性HTML输入字段
- 应该为“容器”元素和“动画”元素分配什么位置属性?HTML CSS JavaScript.
- 动画高度属性::HTML+CSS+JavaScript
- 不能读取属性'HTML'的定义
- 基于类似屏幕的CSS媒体查询更改Javascript属性(HTML中的内联)
- 在 JointJS 中,我得到错误属性 html 在类型“类型形状”上不存在
- 覆盖默认属性'HTML的值"标签,这是由FB js库设置