简体   繁体   English

jQuery $('#id“)不起作用

[英]JQuery $('#id") does not work

I'm a noob in JQuery, trying my hands on the basic functionality of it 我是JQuery的新手,尝试使用它的基本功能

I have a html, like below. 我有一个HTML,如下所示。

<html>
<head>
    <script type="text/javascript" charset="utf-8" src="js/jquery-2.0.3.min.js"></script>
    <script type="text/javascript" src="js/start.js"></script>
    <script>
        $(mainFunction());
        $('#label1').prop('innerHTML', "test");
    </script>

    <title></title>
</head>
<body>
    <label id="label1"></label>
</body>

</html>

From start.js, i'm trying to manipulate the elements in this html file like below. 从start.js,我试图像下面这样操作该html文件中的元素。

function start(name){
    this.iam = name;
    this.getName = function(user){
        return this.iam;
    }
}

function mainFunction(){
    var label = $('#label1');
    var oStart = new start("test");
    label.prop("innerHTML" ,oStart.getName("test"));
}

When I try to lookup whats in the 'label' in the above code, i get [] printed on the console. 当我尝试查找以上代码中“标签”中的内容时,会在控制台上显示[]。 What am I doing wrong here? 我在这里做错了什么?

$(mainFunction()); is your issue. 是你的问题。 Instead provide function reference to document.ready. 而是提供对document.ready的功能引用。

Like this: 像这样:

$(mainFunction);

While doing $(mainFunction()); 在执行$(mainFunction()); you are invoking the function mainFunction while setting up the handler, which means it gets executed too early before the DOM tree has been constructed. 您在设置处理程序时正在调用函数mainFunction ,这意味着在构建DOM树之前过早执行了该函数。

Or in order to avoid confusion you could do: 或者为了避免混淆,您可以执行以下操作:

$(function(){
   mainFunction();
});

Also remember that this issue will not happen if you move your script just before the end of the body tag. 还请记住,如果仅在body标签结尾之前移动脚本,则不会发生此问题。 You do not have to listen to document ready handler. 您不必听文档准备处理程序。 Plus as a shorthand you could just do label.html(oStart.getName("test")); 另外,作为速记,您可以只做label.html(oStart.getName("test"));

You need to wait for the DOM to be ready before using jQuery. 在使用jQuery之前,您需要等待DOM准备就绪。

This is done this way: 这是通过以下方式完成的:

$(document).ready(function() {
  // All your code touching the DOM in here
});

Also note that this line: $(mainFunction()); 还要注意这一行: $(mainFunction()); uses the return value of mainFunction , it does not trigger it when DOM is ready. 使用mainFunction的返回值,在DOM准备就绪时不会触发它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM