最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ajax - Javascript code to preventDefault for all <a href> links - Stack Overflow

programmeradmin1浏览0评论

I am trying to get URLs to change using only Javascript, by updating the content via AJAX.

This is to prevent certain content (namely music, chat message boxes, etc) from refreshing and either

  1. Clearing the place where your music is playing
  2. Resetting something you are working on, like typing a message.

I just began today trying to implement something like this, and so far I've got this:

var a = document.querySelectorAll('a')
for (var i=0; i<a.length; i++) {
   a[i].addEventListener('click',function(event){event.preventDefault();};
}
return false

However, this code

  1. Doesn't allow the url to be changed
  2. Doesn't load the AJAX.

My question is: how do I cancel the age from refreshing, but still allow the url to change?

I am trying to get URLs to change using only Javascript, by updating the content via AJAX.

This is to prevent certain content (namely music, chat message boxes, etc) from refreshing and either

  1. Clearing the place where your music is playing
  2. Resetting something you are working on, like typing a message.

I just began today trying to implement something like this, and so far I've got this:

var a = document.querySelectorAll('a')
for (var i=0; i<a.length; i++) {
   a[i].addEventListener('click',function(event){event.preventDefault();};
}
return false

However, this code

  1. Doesn't allow the url to be changed
  2. Doesn't load the AJAX.

My question is: how do I cancel the age from refreshing, but still allow the url to change?

Share Improve this question edited Jul 18, 2014 at 0:38 Oriol 289k71 gold badges457 silver badges530 bronze badges asked Jul 18, 2014 at 0:29 Tim PowellTim Powell 1271 silver badge11 bronze badges 1
  • getElementsByTagName is faster than querySelectorAll. And avoid inline functions inside loops, at each iteration you create a duplicate function. – Oriol Commented Jul 18, 2014 at 0:34
Add a ment  | 

5 Answers 5

Reset to default 3

Try something like

var a = document.getElementsByTagName('a'),
    ajax;
for (var i=0; i<a.length; ++i) {
   a[i].addEventListener('click', handleAnchor, false);
}
function handleAnchor(e){
    e.preventDefault();
    if(ajax) ajax.abort();
    ajax = new XMLHttpRequest();
    ajax.onload = updateContent;
    ajax.open("get", this.href, true);
    ajax.send();
}
function updateContent() {
    // Do something with `this.responseText`
}

You can try a hash based url scheme:

someurl/#param1

someurl/#param2

...
var anchors = document.getElementsByTagName('a');

for(var i=0; i < anchors.length; i++) {
    addEvent(anchors[i], 'click', preventDefault);
}

function preventDefault(e) {
    e = e || window.event;
   (e.preventDefault)? 
       e.preventDefault() : e.returnValue = false;
}

function addEvent(obj, evType, fn){ 
   if (obj.addEventListener){ 
       obj.addEventListener(evType, fn, false); 
       return true; 
   } 
   else if (obj.attachEvent){ 
       var r = obj.attachEvent("on"+evType, fn); 
       return r; 
 } else { 
       return false; 
 } 
}

Give this a try found this at prevent default for all links inside a div using jquery

Try (this pattern) , utilizing jquery .load()

html

<div class="1">content 1</div><div class="2">content 2</div>
<a class="1" href="#">update 1</a>
<a class="2" href="#">update 2</a>

js

$(function() {
var url = "http://example";
    $("a").each(function(i, el) {
        $(this).on("click", function(e) {
          e.preventDefault();
            if (i === 0) {
              $("div.1")
              .load(url + " #" + $(el).attr("class"));
             };
            if (i === 1) {
              $("div.2")
              .load(url + " #" + $(el).attr("class"));
            };
        })
    });
});

jsfiddle http://jsfiddle/guest271314/dL4b4/

Please try

 $("a[href=#]").click(function (e) {
    e.preventDefault();
 })
发布评论

评论列表(0)

  1. 暂无评论