I'm trying to open a div like a popup, but having it centered at the spot where the mouse was when it triggered the onclick event. In order to get the mouse position, I've been following this example

http://docs.jquery.com/Tutorials:Mouse_Position

jQuery(document).ready(function(){
   $("#special").click(function(e){
      $('#status2').html(e.pageX +', '+ e.pageY);
   }); 
})

in that example, the click function is set client-side. However, in my scenario, I am going to set the onclick function server-side to many dynamically created objects. I will also be adding an argument to my function that will be unique to each object created.

The problem I'm facing is that I can't seem to get the eventargs ("e") when I set the onclick event NOT using JQuery.

Ultimately, a simplified example of what I'm trying to achieve would look something like this:

<div id="divSubscription" style="display: none; height: 0px; width: 0px; position: absolute;">some content</div>     
<input type="button" id="btnOpenPopup" value="Open" onclick='openPopup(8, e)' />

    function openPopup(subID, e) {
        var x = e.pageX;
        var y = e.pageY;
        $("#divSubscription").css("top", y);
        $("#divSubscription").css("left", x);
        $("#divSubscription").css("display", "block");
        $("#divSubscription").animate({ height: "400px", width: "400px" }, 300, "swing");

        $("#divSubscriptionContent").html(subID);
    }

Obviously, this doesn't work, because it has no idea what "e" is. Is there any way to accomplish what I'm trying to do?

有帮助吗?

解决方案

Use class names instead of ids and a data-id attribute to store button specific data (i.e. subID):

CSS:

jQuery(document).ready(function(){
   $(".special").click(function(e){
      var subID = $(this).attr('data-id'); 
      $("#divSubscriptionContent").html(subID);
   }); 
})

HTML:

<div id="divSubscription">some content</div>
<input class="special" data-id="8" type="button" id="btnOpenPopup" value="Open" />

其他提示

Try using delegated events, where #BUTTON_ANCESTOR is the element that contains your buttons:

 jQuery(document).ready(function(){
      $("#BUTTON_ANCESTOR").on('click', 'input[type=button]', (function(e){
           $('#status2').html(e.pageX +', '+ e.pageY);
      }); 
 })

Personally, I think you should remove the onclick and use jquery or some similar framework to attach a click handler and listen for the event.

Simply, with jQuery

$('#btnOpenPopup').bind('click', {foo:bar}, openPopup(e));

Do this in your bootstrap, or initialization process, and get out of the habit of putting your javascript in the html files. IMHO, you should only ever need one script include.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top