I have a file, say 'file1.html', loaded into a div via jQuery $('#info').load('info/file1.html');
I 开发者_如何学编程want to change the content of #info from within file1 so file1.html looks like this:
<a href="#" onclick="loadFile(this.value);" value="file2">File2</a>
where
function loadFile(f) {
$('#info').load('info/'+f+'.html');
}
However, I only get a blank page in the div after the click. I also tried removing the 'info/'
if the folder setup broke it but nothing. What's wrong?
The problem is that anchor tag dom objects (HTMLAnchorElement
) don't have a "value" property set on them. To get at the value attribute of the anchor tag that the dom object represents, you can do $(this).attr('value')
(instead of this.value
, which will just be undefined).
But really, you should be attaching your event using an id/class and jquery, not by using an onclick attribute. And you should be calling your anchor attribute data-value
, not value
, to conform to HTML5 specs on custom attributes. So the better way to do this would be:
HTML:
<a href="#" id="file-loader" data-value="file2">File2</a>
Javascript:
$('#file-loader').click(function(ev) {
$('#info').load('info/' + $(this).attr('data-value') + '.html');
ev.preventDefault();
});
Use:
<a href="#" onclick="loadFile('file2');">File2</a>
精彩评论