简体   繁体   中英

How to make double click & single click event for link button of Asp.net control?

Consider the following:

protected void dgTask_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        LinkButton btn = (LinkButton)e.Row.Cells[4].FindControl("lnkBtnEdit");

        btn.Attributes.Add("onclick", "return Test();");
    }
}

Instead of a single click, how can I make it double click while clicking on the link button?

Edited

I have tried with the solution presented by *competent_tech* but the problem is that in that case it will intercept the single click.

I need to do some operation on single click and something else on double click. Please help me.

Thanks

You'd have to do something like this.

Code behind.

Linkbutton btn;
btn.Attributes.Add("onClick", "OnClick();");

then in your javascript you'll need to define the OnClick function like this

var clickCount = 0;
var timeoutID  = 0;

function OnClick()
{
    clickCount++;

    if (clickCount >= 2) {
       clickCount = 0;          //reset clickCount
       clearTimeout(timeoutID); //stop the single click callback from being called
       DoubleClickFunction();   //perform your double click action
    }
    else if (clickCount == 1) {
       //create a callback that will be called in a few miliseconds
       //the callback time determines how long the user has to click a second time

       var callBack = function(){ 
                         //make sure this wasn't fired at
                         //the same time they double clicked
                         if (clickCount == 1) {      
                            clickCount = 0;         //reset the clickCount
                            SingleClickFunction();  //perform your single click action
                         }
                      };

       //This will call the callBack function in 500 milliseconds (1/2 second).
       //If by that time they haven't clicked the LinkButton again
       //We will perform the single click action. You can adjust the
       //Time here to control how quickly the user has to double click.
       timeoutID = setTimeout(callBack, 500); 
    }
}

You can either put the javascript directly into your .aspx file or add it dynamically when you add the LinkButton to the page. If you need to perform some action on the server side when the user single clicks or double clicks you can use the __doPostBack method. See here for more info on that.

The problem with my approach is that the user will always have to wait the entire callback time before their single click action is performed. I don't see any way around this as long as you are using single click/double click to distinguish what the user wants. If you find this delay to be too big of a problem you could always try something like click/shift+click to alternate between the actions. It probably wouldn't be as intuitive that way but you would immediately know what the user wants and could respond immediately instead of waiting to see if the user clicks a second time.

Let me know if you have any questions.

Short answer: No, you cannot do that.

Long answer: You cannot do that because a double click is effectively 2 single clicks. There are plenty of hacks (such as timer based approaches) that you can find which attempt to do this, but if you choose them, be aware that this is always going to be a non-reliable and risky behavior.

As per quirksmode.org , here's the sequence of events for a double click:

  1. mousedown
  2. mouseup
  3. click
  4. mousedown
  5. mouseup
  6. click
  7. dblclick

Even this order is not consistent amongst browsers. There is simple no reliable way of detecting both click and double click on the same element.

Quoting quirksmode.org :

Don't register click and dblclick events on the same element: it's impossible to distinguish single-click events from click events that lead to a dblclick event.

And per jQuery :

It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.

Your best bet is to redesign the workflow so that you use something else (rather than number of clicks) to rely on.

Try using ondblclick instead of onclick .

To make this work correctly, you also have to intercept onclick and return false so that the automatic navigation does not take place:

        LinkButton1.Attributes.Add("ondblclick", @"alert('test');");
        LinkButton1.Attributes.Add("onclick", @"return false;");

http://jsfiddle.net/XfJDK/2/

<div onClick="return OnClick();">click me</div>
<div id="eventText">...</div>

var clicks = 0;

function OnClick() {

    clicks++;
    if (clicks == 1) 
        setTimeout("RunRealCode();", 300); // schedule real code, allowing for 300ms for 2nd optional click

    setTimeout("clicks = 0;", 350); // click timeout of 300 + 50 ms
}

function RunRealCode() {
        if (clicks == 2)
            $("#eventText").text("Double").fadeOut().fadeIn();
        else if (clicks == 1) 
            $("#eventText").text("Single").fadeOut().fadeIn();
}

Try to get the count of the click and try to perform an operation.i think ondbclick can be implemented through javascript.

int count = 0;
if(btn.Click == true)
{
  count++;
  if(count == 2)
   {
        // Perform the logic here
   }
}

EDIT: What competent_tech said is right.you can perform that logic

将此代码粘贴到Page_Load中即可

LinkButton1.Attributes.Add("ondblclick","yourfunction()"); LinkButton1.Attributes.Add("onclick", @"return false;");

I have placed the example javascript code here.

http://jsbin.com/ubimol/2/edit

Html:

  <input id="sin" type="button" value="Edit" onclick="singleClick();return false;"/>
    <input id="dou" style="display:none" type="button" value="Edit" onclick="doubleClick();return false;" />

Javascript:

var isDoubleClick = false;
function singleClick(){
   $("#sin").hide();$("#dou").show();

  //wait for 500 milliseconds.
  setTimeout("waitForSecondClick()", 500);


}


    function waitForSecondClick(){
    if(isDoubleClick == false){
       alert("this is a sinle click event, perform single click functionality");
      }

      isDoubleClick = false; //Reset
      $("#sin").show();$("#dou").hide();
    }

    function doubleClick(){
      isDoubleClick = true;

      alert("this is a double click event, perform double click funcitonality");



    }

By introducing second button with same value, the solution is stable, but require some extra coding.

您可以使用此处给出的Jquery事件双击打开链接可以在此处找到文档http://api.jquery.com/dblclick/

In testing your example above, I found that the form the GridView is contained in gets submitted every time you click the LinkButton . To work around this I have used the following code.

The following script will count each time the user clicks the link.

<script type="text/javascript">    
    var clickNo = 0;    

    function clickCounter() {    
        clickNo++;    
        if (clickNo == 2) {    
            alert("Double Click");    
            clickNo = 0;    
        }    
    }    
</script>    

We cancel the form submission so that we can track the number of times the user clicks the link. This may cause problems with your page, but appears to be the reason why the double clicks cannot be tracked.

<form id="form1" runat="server" onsubmit="return false;">    

I created a template field in a GridView control to show both the single click and double click buttons.

<asp:TemplateField HeaderText="Edit">    
    <ItemTemplate>    
        <asp:LinkButton ID="lnkBtnEdit" runat="server">LinkButton</asp:LinkButton>    
        &nbsp;&nbsp;    
        <asp:LinkButton ID="lnkBtnEditDouble" runat="server">LinkButton</asp:LinkButton>    
    </ItemTemplate>    
</asp:TemplateField>    

In the code behind the page we add the javascript code for a single click and the javascript code for a double click. Please note: the Cell reference is set to 2 whereas in your example it was 4, due to the limited columns I used in my testing.

try     
{    
    if (e.Row.RowType == DataControlRowType.DataRow)    
    {    
        // Please note: the value in Cells has changed for my testing data.    
        LinkButton btn = (LinkButton)e.Row.Cells[2].FindControl("lnkBtnEdit");    

        btn.Attributes.Add("onclick", "javascript:alert('Single Click');");    

        LinkButton btnDouble = (LinkButton)e.Row.Cells[2].FindControl("lnkBtnEditDouble");    

        btnDouble.Attributes.Add("onclick", "javascript:clickCounter();");    
    }    
}    
catch (Exception ex)    
{    
    Console.WriteLine(ex.Message);    
}    

This should allow you to capture double clicks on some links and single clicks on others. However, as mentioned above, the form submission is now cancelled and you will need to find another method to submit your data if you are to use the above code.

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