如何使用 href 并单击侦听器进行收集
How to use href and click listener togather?
我有一个链接列表,每个链接都有href属性:
<a href="./page1.php" class="points">page 1</a>
<a href="./page2.php" class="points">page 2</a>
<a href="./page3.php" class="points">page 3</a>
<a href="./page4.php" class="points">page 4</a>
我有一个类"点"的侦听器:
$(".points").live('click',function(){
id = $(this).attr("id");
$.ajax({
type: "POST",
url: 'points.php',
data:{id:id},
success: function()
{
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);
}
});
});
href 有效,但点击不起作用,当我删除 href 属性时,点击侦听器工作正常。那两个人有没有可能合作?
试试这个:
$(".points").live('click',function(e){ //added e as function argument
e.preventDefault(); //added preventDefault();
var id = this.id; // changed here to this.id, and added var (so it will be a local variable)
$.ajax({
type: "POST",
url: 'points.php',
data:{id:id},
success: function()
{
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);
}
});
});
- 阅读有关 preventDefault() 的信息
- 请注意,
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
您需要取消默认行为,因为当您导航离开的那一刻,脚本将停止运行。 您可以考虑等到 Ajax 调用完成,然后通过脚本进行导航:
$(".points").live('click',function(e){ // <--- Add e parameter
e.preventDefault(); // <--- Add this
id = $(this).attr("id");
href = $(this).attr("href"); // Link we will navigate to when done
$.ajax({
type: "POST",
url: 'points.php',
data:{id:id},
success: function()
{
location.href = href; // Do the navigation now that we're done
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);
}
});
});
让 Ajax 和 Href 一起工作
尝试
$(".points").live('click',function(e){
e.preventDefault();
var id = $(this).attr("id");
var url= $(this).attr("href");
$.ajax({
type: "POST",
url: 'points.php',
data:{id:id},
success: function()
{
//Do something before going to page
window.location.href=url;
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);
}
});
});
相关文章:
- 如果侦听器附加到父元素,是否可以区分单击发生在哪个子元素上
- 谷歌地图v3侦听器(单击)-更改URL
- 为左键或右键单击附加事件侦听器-onclick'右键单击无效
- 单击时的Javascript事件侦听器未按预期工作
- 单击“ExtJS”中的“事件/侦听器”
- 关闭菜单,单击带有事件侦听器和父节点的正文
- Ext JS,项目单击侦听器似乎不起作用
- 在“JQuery 模式”对话框中指定图像单击侦听器
- Javascript 单击侦听器获取类
- 单击事件侦听器关闭困难
- 事件侦听器单击不起作用
- 如何使用 href 并单击侦听器进行收集
- 事件侦听器在单击/提交时未触发
- 单击链接时的 Javascript 操作顺序 - 链接启动或附加到 id 的侦听器触发
- 阻止 JQuery 单击侦听器
- Jquery (2.2.0) 单击侦听器在使用 .on() 时单击几下后停止工作,但 .click() 工作正常
- j查询输入按钮单击事件侦听器
- 侦听器单击任何元素并读取特定的 HTML-5 自定义属性(如果存在)
- 如何在事件侦听器单击后将ID传递给函数
- 谷歌地图标记事件侦听器点击