1

I try to change some links on a webpage using the following code for jQuery on Rails

$(function () {
  $('#lesson a').live('click', function () {
    $.getScript(this.href.replace(/^(http...[^\/]+)?\/+(.*)$/,'/ajax/\\$2'));
    return false;
  });
})

This trick works for Chrome and Safari, but fails (nothing happens on click) for Firefox and Opera. What can be wrong with the code?

EDIT1:

The webpage contains:

<div id="lesson">
  <a href="/subj1">Subject 1</a>
  ...
</div>

On click, a browser (i.e. Firefox and Opera) should make an ajax-request of /ajax/subj1.

7
  • Can you include source of an example HTML page as well? Commented Jan 12, 2011 at 20:22
  • @orangepips, Just did it. Please, see the updated question. Commented Jan 12, 2011 at 20:27
  • 2
    In what way does it fail? What errors do you receive? Commented Jan 12, 2011 at 20:27
  • instead of returning false you should function(e) { e.preventDefault(); /* your code */} Commented Jan 12, 2011 at 20:28
  • @lonesomeday, nothing happens after click Commented Jan 12, 2011 at 20:31

1 Answer 1

2

You replace the string with '/ajax/\\$2'.
You have an extra backslash - if you expect the result /ajax/subj1, use '/ajax/$2'.

2
  • thanks! I've misread how one refers a regex part in javascript. It is interesting that it worked for some browsers. Commented Jan 13, 2011 at 7:52
  • 1
    @Andrei - no problem! Sometimes you write something, and then blinded by it - even though it's right in your face :). Some browsers are very forgiving - they correct urls and even html, assuming the user mistyped it. For example, http:/google.com will work in most browsers, even though it isn't a valid url. IE auto corrects \ to / (or at least did 7 years ago - hadn't checked since), and probably collapses // to /, giving a correct result. Commented Jan 13, 2011 at 7:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.