2010-11-19 5 views
6

I have numerous anchor tags on my page that only trigger jQuery actions on the same page.Альтернатива <a href="#"> when the anchor tag only triggers a jQuery action without redirecting the user?

The don't redirect the user to another location, which is the normal expected behavior of an anchor tag.

I don't want to have restful urls in my app for every action. But, I also don't like sending the user to the top of the page every time they click on one of these <a href="#"> tags.

What's a better value to put inside the href value of the anchor tag besides #?

+0

ли вы найти решение или мой ответ, что вы реализовали? Если это было бы неплохо, если бы вы могли отметить это как решение. :-) –

ответ

1

# is fine. But the callbacks that are triggered should then return false.

// assigning a click callback to all anchors 
    $('a').click(function(evt){ 
     //... do stuff 
     return false; // avoid jump to '#' 
    }) 
1

I prefer to use:

<a href="javascript:">foo</a> 

unless it is actually an ajax call to load a partial template in which case I use something like this:

<a href="/link/to/page" onClick="ajax_request_to_partial(); return false;">foo</a> 

By returning false in the onclick event, you make sure the site is not reloaded, but it can still be used for opening the url in a new page.

+0

* href = "javascript:" * перерывы в Firefox в более поздних версиях. Я не уверен, когда они меняют это, но я надеюсь, что есть альтернатива, потому что * # * нарушает пользовательский интерфейс, перескакивая вверх страницы вверх страницы. – Typel

+1

'javascript: void (0)' –

9

Can you reference a fragment on the page that could work as a logical fallback to the non-executed JavaScript action? If so, it makes a lot of sense to reference <a href="#account"> and have an id="account" on the page that could work as a fallback.

Another option is to reference the dynamically loaded content directly; that way you can quite conveniently use the href in the Ajax call instead of hard-coding what to request in JavaScript somehow; <a href="/path/to/dynamic/content">.

Lastly, you can not have the <a href="#"> statically in the HTML at all, but instead create it on the fly with jQuery since it's only used by jQuery anyway. No need to pollute the markup with placeholders for JavaScript if the placeholders are only used by and for JavaScript anyway.

Regarding "sending the user to the top of the page"; you should just return false from your the function you have hooked up as a click() handler;

$('a').click(function() { 
    // Do your stuff. 
    // The below line prevents the 'href' on the anchor to be followed. 
    return false; 
}); 
0

if you bind some action on click on you can call preventDefault() to avoid sending user in top of page

$("a.clickable").live('click',function(){$(this).doSome(); $(this).preventDefault()}); 
2

If you have links that aren't links, perhaps they shouldn't be links? :-) You might consider a different UI element that doesn't have a default behavior (outside of a form), like button (you can style buttons to a substantial degree). Or you could use span or similar, but if you do be sure to set the appropriate accessibility information (such as an ARIA role="link"), чтобы вы не испортили устройства чтения с экрана (и вкладки браузера).

Но если вы хотите продолжить использовать <a href="#">...</a>, просто прикрепите к ним обработчик, который вызывает event.preventDefault(); или возвращает false.

1

Если якорь бесполезен для людей, у которых нет javascript, тогда они не должны его видеть.

Лучшей альтернативой является создание этих ссылок с использованием jQuery при загрузке страницы - таким образом, только те, кто их видит, - это те, кто их будет использовать.

В этом случае, имея href="#" это хорошо, потому что до тех пор, как ваш обработчик события заканчивается не return false; того href не будет следовать

5

Вы должны быть действительно используя <button> элемент для JS-только действий. У них есть действие по умолчанию (если внутри формы), но вне формы они предназначены исключительно для инициированных пользователем действий, к которым вы привязываете обработчик событий JS.

+1

Я действительно был очень удивлен, увидев, что 'button' имеет поведение по умолчанию, если у него нет атрибута' type', и все же это похоже на то, что текущий проект spec говорит: http://www.w3.org/TR/html5/the-button-element.html#the-button-element. Я всегда считал, что отсутствующее значение по умолчанию для 'type' на' button' элементах было 'button' , а не 'submit'. Благодарю. –

1

Вы пробовали исключить параметр href?

<a>Link title</a> 

Это должно работать нормально и не заставлять браузер загружать веб-страницу или изменять положение страниц. На самом деле он ничего не сделает, если у вас нет JavaScript для его поддержки.

Параметр href необязателен, поэтому зачем включать его, если вы его не используете?

+0

Укладка якоря (фактически любого объекта html) не имеет ничего общего с параметрами, которые он содержит. с вне href будет выглядеть точно так же, как RAC

+0

Это не в Chrome. Я не тестировал его в других браузерах, поэтому я могу ошибаться * shrug * – williamle8300

0

Я использую ниже код и работает нормально.

<div class="panel-heading">Definition 
      <div class="pull-right"> 
       <i class="fa fa-wrench"></i> 
       <a id="step3Ad" href="javascript:void(0);">Advanced</a> 
      </div> 
    </div