简体   繁体   中英

Strange SVG / javascript behavior

I might be missing something essential here.

I am changing the date format in some SVG text elements with this function.

jQuery.fn.fixDateformat = function(){
        ar = $(this).text().split("/")
        output = [ar[1], ar[0], ar[2]].join(".")
        $(this).text(output)
    };

In the console I get an array of the elements I want to change.

> array = $("text[x='0']")
[
<text y=​"5" dy=​".71em" text-anchor=​"middle" x=​"0">​04/21/13​</text>​, 
<text y=​"5" dy=​".71em" text-anchor=​"middle" x=​"0">​04/26/13​</text>​, 
<text y=​"5" dy=​".71em" text-anchor=​"middle" x=​"0">​05/02/13​</text>​, 
<text y=​"5" dy=​".71em" text-anchor=​"middle" x=​"0">​05/08/13​</text>​, 
<text y=​"5" dy=​".71em" text-anchor=​"middle" x=​"0">​05/14/13​</text>​
]

When I pass the function to one of elements it works. Yeay!

> array.first().fixDateformatOnCharts()

But, when I loop through the array I get this error.

> array.each(function(i,v){ v.fixDateformatOnCharts()})
TypeError: Object #<SVGTextElement> has no method 'fixDateformatOnCharts'

Any ideas?

You should use $(v) to convert an element v to a jQuery object.

array.each(function(i,v){ $(v).fixDateformatOnCharts(); });

Maybe it would be better to add this funcionality to the plugin itself:

jQuery.fn.fixDateformat = function() {
  return this.each(function(i, el) {
    ar = $(el).text().split("/");
    output = [ar[1], ar[0], ar[2]].join(".");
    $(this).text(output);
  });
};

So you can use array.fixDateformat(); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM