本文介绍了试图让jQuery加载工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我浏览菜单时,我只希望更改contentarea div,而不要重新加载整个页面.我想使用jquery加载函数从另一个页面(从members.html div colTwo)读取一个div并将其插入到页面中(进入div contentarea).我一直在尝试,但无法正常工作.

When I navigate through the menu I want only the contentarea div to change and not reload the whole page. I want to use the jquery load function to read a div from another page (from members.html div colTwo) and insert it onto the page (into div contentarea). I have been trying but couldn't get it to work.

任何编辑此脚本的帮助都会有所帮助!

Any help editing this script would be helpful!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Title</title>
<link href="default.css" rel="stylesheet" type="text/css" />
</head>

<script type="text/javascript" src ='http://code.jquery.com/jquery-1.9.1.min.js'</script>
<script type="text/javascript">
$(document).ready(function() {
function memberspage(){
    $('#contentarea').load('members.html #colTwo');
}
});
</script>

<body>
<div id="header">
    <h1>My Title</h1>
</div>
<div id="content">

    <div id="colOne">

        <div id="menu1">
            <ul>
                <li><a href="#" onclick='memberspage()'>Members</a></li>
            </ul>
        </div>
        <div class="margin-news">
            <h2>Recent Updates</h2>
            <p><strong>None At This Time</strong> </p>
        </div>
    </div>

    <div id="contentarea"><h2>Starting Text</h2></div>
    <div style="clear: both;">&nbsp;</div>
</div>

</body>
</html>

推荐答案

问题是您已经在文档就绪处理程序中声明了memberspage()函数,这意味着您尝试调用它时不在范围内从锚元素上的内联onclick处理程序中获取-这样的内联属性只能访问全局函数.

The problem is that you've declared your memberspage() function inside a document ready handler, which means that it is not in scope when you try to call it from an inline onclick handler on your anchor element - inline attributes like that can only access global functions.

您可以通过将函数声明从准备就绪的文档中移出(使其变为全局)来解决此问题,但是更好的选择是将单击处理程序与jQuery绑定:

You can fix this by moving the function declaration out of the document ready (making it global), but a better option would be to bind the click handler with jQuery:

$(document).ready(function() {
    $("#menu1 a").click(function(e){
        $('#contentarea').load('members.html #colTwo');
        e.preventDefault();
    });
});

我添加了e.preventDefault()来停止锚点单击的默认行为,否则可能会滚动回到页面顶部. (在内联处理程序中,通过返回false将获得相同的效果.)

I've added e.preventDefault() to stop the default behaviour on the anchor click which might otherwise scroll back to the top of the page. (In an inline handler you would get the same effect by returning false.)

还请注意,包含jquery.js的<script>元素在结束</script>之前丢失了结束>.

Note also that your <script> element that includes jquery.js is missing a closing > right before the closing </script>.

这篇关于试图让jQuery加载工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:42