[英]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?
我知道我可以为每个函数编写一个javascript函数并使用“ onclick”,但是有没有一种好的方法来编写一个函数来完成正在执行的操作?
HTML: 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 工作示例: Vanilla Javascript或jQuery
Add the class areyousure, and the text you want in the question to each anchor as a rel
attribute. 将类areyousure和想要的问题文本添加到每个锚点作为
rel
属性。
<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. 然后使用此javascript构造问题,如果用户按“取消”,它将返回false,从而阻止该操作。
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 如果您使用jQuery
$('.areyousure').on('click', function(){
var q='Are you sure you want to ' + this.rel + ' this item?';
if (!confirm(q)) return false;
})
Why rel
? 为什么要
rel
? Because it's valid HTML and you're not already using it. 因为它是有效的HTML,并且您尚未使用它。 Normally I'd use jQuery always so would assign a data tag instead.
通常我总是使用jQuery,所以会分配一个数据标签。
You can use jQuery to validate stop the link processing if the user says no, something like: 如果用户拒绝,您可以使用jQuery验证停止链接处理,例如:
$('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/ 我已经发布了一个小提琴http://jsfiddle.net/dtymH/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.