[英]jquery function reloads the page on click event
I am having a problem. 我遇到了问题。 Below is my code: 以下是我的代码:
$(function() {
$('#find').on("click",function(){
name = $('#q_name').text();
location = $('#q_location').text();
city = $('#q_city').text();
alert("Clicked");
});
});
When this anchor tag whose id
is find
is clicked the alert "Clicked" appears then the whole page is reloaded. 当点击find
id
锚标签时,会出现警告“Clicked”,然后重新加载整个页面。 I am getting name, location and city values from p
tags separately. 我分别从p
标签获取名称,位置和城市值。
Also when I keep only one assignment and discard other two then page reloading stops and only alert occurs. 此外,当我只保留一个分配并丢弃其他两个分配时,页面重新加载停止并且仅发生警报。 This is the beginning as I have to send this collected data to via AJAX to controller function but first I want to stop reloading the page. 这是开始,因为我必须通过AJAX将这些收集的数据发送到控制器功能,但首先我想停止重新加载页面。 What am I doing wrong? 我究竟做错了什么?
PS: I'm very new to jQuery and only know few of its basics. PS:我对jQuery很新,只知道它的基础知识。 Please help. 请帮忙。
You need to stop the default behaviour of the link (ie. changing the URL) by using event.preventDefault
, try this: 您需要使用event.preventDefault
停止链接的默认行为(即更改URL),请尝试以下操作:
$('#find').on("click", function(e){
e.preventDefault();
name = $('#q_name').text();
location = $('#q_location').text();
city = $('#q_city').text();
alert("Clicked");
});
Rename your location
variable to location1
. 将您的location
变量重命名为location1
。 i think it refer to browser location. 我认为它指的是浏览器位置。
try this. 尝试这个。 simple and easy 简单易行
Modify the href attribute as given below 修改href属性,如下所示
<a href="javascript:void(0)" onclick="whateverFunction()" >
To stop the page reload and navigation behavior of anchor tag, you can use javascript:void(0)
or event.preventDefault() 要停止锚标记的页面重新加载和导航行为,可以使用javascript:void(0)
或event.preventDefault()
<a href="javascript:void(0)" id="find">Click</a>
Or 要么
$(function() {
$('#find').on("click",function(e){
e.preventDefault()
name = $('#q_name').text();
location = $('#q_location').text();
city = $('#q_city').text();
alert("Clicked");
});
});
Now your page will not reload on click on this anchor tag. 现在,点击此锚标记后,您的页面将不会重新加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.