Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

jquery - Click event for SVG rectangle

I'm using SVG together with jQuery in my Mvc Application. I draw a series of rectangles on my page and what I would like to do is attach a click or mouseover event for each rectangle, for say, popup an alert box. I've tried something like this, so far:

$("rect[id='Y6']").attr('onclick', function() { alert("Hello!") });

and

$("rect[id='Y6']").live('click', function() {    
    alert("Hello!");
};

But sadly none of this events really worked for this control. Does anyone know how to do this?

EDIT:

I'm adding the javascript code I'm using below:

<script type="text/javascript">
    /*function resetSize(svg, width, height) {
        svg.configure({ width: width || $(svg._container).width(),
            height: height || $(svg._container).height()
        });
    }*/
    function onLoad(svg, error) {
        //svg.text(10, 20, error || 'Loaded into ' + this.id);
        //resetSize(svg, null, null); //'100%', '100%');
    }

    $(function() {
        $('#layout').svg({});

        var svg = $('#layout').svg('get');
        svg.load('<%= Url.Action("Layout", new{ id = Model.Id }) %>', { //<%= Url.Content("~/media/svg/lion.xml") %>', {
            addTo: false,
            changeSize: false,
            onLoad: onLoad
        });
    });    

$('rect#Y6').click( function(){
  alert('hello');
});

</script>

The rectangles are loaded from a svg picture.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code to add the click handler needs to be part of the onLoad function - with that change it works for me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...