jQuery-停止锚点<a> from redirecting using onClick=&#34;function(this)&#34;

时间:2019-01-07 17:06:03

标签: javascript jquery codeigniter

this is my anchor i am using in CodeIgnitor pagination.

<a href="http://perfex_crm.ng/clients/get_front_page_jobs/2" onclick="myFunction(this)" data-ci-pagination-page="2">2</a>

now this is the definition of function in Javascript

function myFunction(e){
    console.log(e);
    e.preventDefault()
}

Now e is an anchor which is shown in the console. but when i try

e.preventDefault()

it gives me this error.

e.preventDefault is not a function

and obviously page redirected which is original problem i want to solve. i do not want it to redirect.

3 个答案:

答案 0 :(得分:4)

您传递的是this元素对象<a>的值,而不是事件对象。

您可以改为传递event,但您实际上应该避免使用固有事件属性(具有很多陷阱)并切换到addEventListener

const links = document.querySelector('[data-ci-pagination-page]');
for (let i = 0; i < links.length; i++) {
    links[i].addEventListener(myFunction); 
}

答案 1 :(得分:2)

自从您编写了onclick="myFunction(this)"之后,您就将this作为参数传递,其中this是您的<a>元素。

尝试通过event代替:onclick="myFunction(event)"

答案 2 :(得分:1)

这似乎很吸引人:

function myFunction(event){
  event.preventDefault();
}
<a href="http://perfex_crm.ng/clients/get_front_page_jobs/2" onclick="myFunction(event)" data-ci-pagination-page="2">2</a>