简体   繁体   中英

Get the closest element to a SVG node using Jquery closest() function

I have the following code:

 $(document).ready(function () {

    var svg = d3.select("svg");

    svg.append("circle")
            .attr("class","cursor")
            .attr("r", 8)
            .attr("cx", 100)
            .attr("cy", 100)
            .on("click", test);

    function test(d)
    {
        f = d3.select(this);

        console.log($(f).closest('svg').css('border-color','red'));


    }

});

I noticed that it doesn't work. But if I execute the same function on a non SVG element (regular html element like div or canvas...) it does what it is supposed to do. I first thought that the problem was the d3 selection. I then parsed the element directly with the class attribute like:

console.log($('.cursor').closest('svg').css('border-color','red'));

Without success.
Is there a way to make the jquery closest() function work with element inside SVG tag ?

Thank you

Wrapping a d3 selection in $ is invalid. Use $(this) instead of $(f) . The this keyword in the click handler is set to the clicked DOM element, which is what you need.

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