Javascript/Jquery 属性选择器
我需要找到一个可以动态创建并且是 DOM 一部分的元素,并更改它的一些属性。我正在 svg 元素上尝试它,但你在 Javascript /Jquery 方面的专业知识会对我有所帮助。
<svg id="cvs" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" >
<rect uid="id1" class="cont" x="0" y="0" width="200" height="200" />
</svg>
在运行时,我添加了一些更多的矩形元素,例如
var el = document.createElementNS(svgNS,'rect');
//set the attribues including uid //say id2, id3 etc
svg.appendChild(el);
现在,我需要编写一个更新方法,它根据 uid 匹配矩形元素,设置所有属性。
updateRect = function(properties){
$('rect[uid="' + properties.uid + '"]') {
for (var p in properties) {
this.setAttribute(p,prop[p]);
}
}
};
它更多的是一个伪代码来表明我的意图。我不确定它是否也会找到动态创建的元素。有更好的逻辑吗?我不必使用 jQuery,但任何 JS sol 将不胜感激。
编辑1: 选择器可能正在工作,但我对如何链接所选对象上的操作有点迷失。
类似的东西,
var el = $('rect[uid="' + properties.uid + '"]')
if el.exist() {
//do the operation
}
或者更好的方法???谢谢... 谢谢, bsr。
I need to find an element, which could be created dynamically and part of DOM, and change few of its attributes. I am trying it on svg elements, but your expertise in Javascript /Jquery would help me.
<svg id="cvs" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" >
<rect uid="id1" class="cont" x="0" y="0" width="200" height="200" />
</svg>
At run time, I add few more rect elements like
var el = document.createElementNS(svgNS,'rect');
//set the attribues including uid //say id2, id3 etc
svg.appendChild(el);
Now, I need to write an update method, where it matches the rect elelement based on uid, sets all the attribues.
updateRect = function(properties){
$('rect[uid="' + properties.uid + '"]') {
for (var p in properties) {
this.setAttribute(p,prop[p]);
}
}
};
It is more of a pseudo code to show my intentions. I am not sure whether it would find the dynamically created elements as well. Is there a better logic? I don't have to use jQuery, but any JS sol would be highly appreciated.
Edit 1:
The selector may be working, but I am bit lost in how can I chain the operation on the selected object.
something like,
var el = $('rect[uid="' + properties.uid + '"]')
if el.exist() {
//do the operation
}
or a better way??? thanks...
thanks,
bsr.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Iiuc 你想要做的是:
或
取决于你是否想要处理 jQuery 包装器或 DOM 元素。
Iiuc what you wish to do is:
or
depending on whether you want to handle the jQuery wrapper or the DOM element.
当然它应该找到任何新添加的 DOM 元素 - 不知道为什么它不会选择它..
我会进入 firebug 并只需输入
$("rect") 并查看是否显示任何内容,然后查看属性并查看发生了什么事
Sure it should find any newly added DOM elements -- not sure why it won't select it..
I would go into firebug and just type
$("rect") and see if anything shows up, then look into the attributes and see what's goin on