【问题标题】:Is this Syntax Correct这个语法正确吗
【发布时间】:2011-12-25 06:39:40
【问题描述】:
    for(var div_count=0;div_count<10;div_count++)
        {
            $("#div_"+div_count).append("<div style="'margin-left:'+incr_count+"px;>Hello<div>");
            incr_count=incr_count+ 80 ;            

        }

上面的代码不工作。但是当我将值硬编码为margin-left时。有用。我认为这是一个语法 pblm。谁能纠正我。

谢谢。

【问题讨论】:

    标签: javascript jquery html css web


    【解决方案1】:

    将第三行改为:

    $("#div_"+div_count).append("<div style='margin-left:" + incr_count + "px;'>Hello</div>");
    

    【讨论】:

    • 你的答案不完整!他在做incr_count=incr_count+ 80px ; ,这将是作业中的两个“px”字。
    【解决方案2】:
    incr_count = 0;
    for(var div_count = 0; div_count < 10; div_count++) {
        $("#div_" + div_count).append(
                                    $("<div>")
                                        .css("margin-left", incr_count + "px")
                                        .html("Hello")
        );
        incr_count += 80;       
    }
    

    【讨论】:

    • 酷。我也试过这个。但我不知道在哪里放置.css。我把它放在应用于父元素的外部附加中。感谢您的代码。
    • +1 用于显示使用 jquery 设置样式属性的正确方法
    【解决方案3】:
    for(var div_count=0;div_count<10;div_count++)
            {
                $("#div_"+div_count).append('<div style="margin-left:'+incr_count+'px;">Hello</div>');
                incr_count=incr_count+ 80 ;            
    
            }
    

    【讨论】:

    • 您在样式属性周围缺少引号,并且您有一个未关闭的&lt;div&gt;
    • @Anish 哪一个?选择一个回答最有帮助的人; (包括第三行的修复)
    • 我尝试了你的两个答案。但是你的答案更具体,你指出了 px (我没有在我的实际代码中使用)。无论如何,我接受你的两个答案。
    • 你能解释一下上面的代码(即代码中使用的引号)吗?我不知道在哪里放引号...
    • 要使用的 HTML 代码是 &lt;div style='margin-left: 80px;'&gt;Hello&lt;/div&gt;。所以要用Javascript写出来,你需要把它变成一个字符串的连接。第一个字符串是"&lt;div style='margin-left:"。然后我们将它与变量incr_count 连接起来。最后,添加最后一个字符串:"px;'&gt;Hello&lt;/div&gt;"。如果您无法像这样可视化事物,请先编写基本 HTML,然后将其拆分。
    猜你喜欢
    • 2011-05-08
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多