I would like to load content of a main <div>
when user clicks on an <a>
element.
This is the menu item structure, with the <a>
element and some non-working code to try to further explain the question:
<li>
<a href="#" onclick="menu_foo()">
<span>Foo Menu</span>
</a>
<script type="text/javascript">
function menu_foo() {
$('#main_panel').load('/foo');
}
</script>
</li>
The items of the menu are generated dynamically, hence the < script > has been located next to the <li>
item.
The specific question is related to how to make an <a>
element launch a JavaScript function.
答案 0 :(得分:1)
使用jquery点击处理程序并在点击时加载文件。 $(“a”)选择所有锚点,因此您可能希望在标记上附加一个类或id。
<a id="one" href="#" onclick="menu_foo1()">
<span>Foo Menu</span>
</a>
<a id="two" href="#" onclick="menu_foo2()">
<span>Foo Menu</span>
</a>
<a id="three" href="#" onclick="menu_foo3()">
<span>Foo Menu</span>
</a>
$('#one').click(function(){
$('#main_panel').load( '/foo1' );
});
$('#two').click(function(){
$('#main_panel').load( '/foo2' );
});
$('#three').click(function(){
$('#main_panel').load( '/foo3' );
});
答案 1 :(得分:1)
您无需动态生成脚本。只需生成a
href
即可链接到您要加载的网页。
<a id="load" href="/foo1">
<span>Foo Menu</span>
</a>
<script>
$("#load").click(function(e){
e.preventDefault ();
$("#main_panel").load($(this).attr("href"));
});
<script>