简体   繁体   中英

Changing text of prompt based on link clicked by user

I'm working on a site that has a queue of "to do" items, which users can edit, claim, or mark as finished. I want a simple prompt when the user clicks the link to perform one of those actions that says "are you sure you want to [action] this item?". I know I can write a javascript function for each and use "onclick", but is there a nice way to write one function that fills in the action being done?

HTML:

<table>
  <tr>
    <td id='complete'>
        <a href='submit.php?request=$request_index'><img src='images/completeCheck.gif'/></a>
    </td>
    <td>
        <a href='claim.php?request=$request_index'><img src='images/claimStar.gif'/></a>
    </td>
  </tr>
</table>

Working examples: Vanilla Javascript or jQuery

Add the class areyousure, and the text you want in the question to each anchor as a rel attribute.

<table>
  <tr>
    <td id='complete'>
        <a class='areyousure' href='submit.php?request=$request_index' rel='complete check'><img src='images/completeCheck.gif'/></a>
    </td>
    <td>
        <a class='areyousure' href='claim.php?request=$request_index' rel='claim star'><img src='images/claimStar.gif'/></a>
    </td>
  </tr>
</table>

Then use this javascript to construct the question and if the user presses cancel it will return false, preventing the action.

var areyousures = document.getElementsByClassName('areyousure');
for (i in areyousures) {
    var item = areyousures[i];  
    item.onclick=function(){
       var q='Are you sure you want to ' + this.rel + ' this item?';
       if (!confirm(q)) return false; 
    }
}

If you use jQuery

$('.areyousure').on('click', function(){
    var q='Are you sure you want to ' + this.rel + ' this item?';
    if (!confirm(q)) return false;
})

Why rel ? Because it's valid HTML and you're not already using it. Normally I'd use jQuery always so would assign a data tag instead.

You can use jQuery to validate stop the link processing if the user says no, something like:

$('a').click(function(evt) {
   var res = confirm('Are you sure you want to ' + $(this).text());
    if (!res) {
       evt.preventDefault();
    }
});

I've posted a fiddle http://jsfiddle.net/dtymH/1/

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