0

I think this error must be very silly, but I've been trying over three hours and do not get it to work. I have some li elements, its text tells me what file to load: the files to load are stored in the same directory as the script. I want that when clicking the li, the content division is populated with the contents of the file with the same name as the text of the li. This is my code, can someone help me, please, what I'm doing wrong?

<ul class="sample_list">
    <li>AudioContext.txt</li>
    <li>AudioNode.txt</li>
    <li>AudioDestinationNode.txt</li>
    <li>AudioBuffer.txt</li>
</ul>

<div id="content"></div>


<script type="text/javascript">
    $(".sample_list li").click(function(){
        $("#content").load($(this).text());
    });
</script>
gines capote
  • 1,110
  • 1
  • 8
  • 12
  • 1
    Try putting script in document.ready – Adil Jun 17 '14 at 12:04
  • 1
    Have you tried using the full path to the file? Also if you are trying this in file:/// environment you might get browser sandbox errors. – Alexander Kludt Jun 17 '14 at 12:10
  • Yes, I've tried that. If I call the .load sentence outside the $(".sample_list li").click(function() it works, so that that's not a problem of incorrect link. – gines capote Jun 17 '14 at 12:24

2 Answers2

0

Wrap your listener in the document ready event of jQuery. Additionally, declare the text variable in advance. Sometimes jQuery(this) can be tricky in terms of scope. If you call for jQuery(this) inside a method for the #content element, you're addressing that element, not the li you clicked.

$(document).ready(function() {
    $(".sample_list li").click(function(){
        var text=$(this).text();
        $("#content").load(text);
    });
});

You can see it working here: http://ffflabs.com/sandbox/loadli.html

ffflabs
  • 17,166
  • 5
  • 51
  • 77
  • i've tried that, but does not work. I've tried to write $("#content").load("AudioContext.txt"), but it doesn't work inside the li click function. If I try it outside de $(".sample_list li").click(function(), it works, but inside it doesn't. – gines capote Jun 17 '14 at 12:21
  • It worked for me in my localhost. I'll upload it to a public server to show you. – ffflabs Jun 17 '14 at 12:35
  • Ok, thank you very much. Now it works. I don't know what's happening. The same code I've posted in the original question, now works. – gines capote Jun 17 '14 at 13:22
  • Perhaps it was uploaded to the server, but the browser kept displaying outdated html due to cache configuration. That, or proper refresh magic. – ffflabs Jun 17 '14 at 15:42
  • Yes, I think that was what happened. Originally mi
  • were like this:
  • AudioContext
  • , I'd simplified the problem for the question. The thing is if you don't write the "#" in the href, the script does not function. If you write it it does. So I think that the browser did cache the error and after that the code I ship with the question did not work at all. – gines capote Jun 17 '14 at 16:30