如何使这段代码更具可读性

发布于 2024-11-07 06:35:56 字数 859 浏览 8 评论 0原文

这是php代码的一部分,它使用contentArray,它是一个JSON,并向用户生成UI,它生成html标签,也生成js代码......它有效,但我认为代码很难阅读和维护,有什么想法吗???谢谢。

for($i = 0; $i < count($contentArray); $i++){  

    if($i %2 == 0){
       echo ("<li class='even_row'>");
    }else{
       echo ("<li class='odd_row'>");
    }  
    $content = $contentArray[$i];    

    echo("<textarea class='userdata' id='user_data_textarea_".$content->{'m_sId'}."'>");
    echo($content->{'m_sDataContent'});  
    echo("</textarea>"); 

echo("</li>");   

    echo("<script type='text/javascript'>");

    echo("$('#user_data_textarea_".$content->{'m_sId'}."').bind('keydown', function(e){");  
    echo("  TypingHandler.handleTypingInUserDataTextArea(".$content->{'m_sId'}.", e);");
    echo(" });");    

    echo("</script>");

}            

This is a part fo php code, which use the contentArray, which is a JSON, and generate the UI to the user, it generate html tags, also, it generate js code too.... It works, but I think the code is pretty difficult to read and maintain, any ideas??? thank you.

for($i = 0; $i < count($contentArray); $i++){  

    if($i %2 == 0){
       echo ("<li class='even_row'>");
    }else{
       echo ("<li class='odd_row'>");
    }  
    $content = $contentArray[$i];    

    echo("<textarea class='userdata' id='user_data_textarea_".$content->{'m_sId'}."'>");
    echo($content->{'m_sDataContent'});  
    echo("</textarea>"); 

echo("</li>");   

    echo("<script type='text/javascript'>");

    echo("$('#user_data_textarea_".$content->{'m_sId'}."').bind('keydown', function(e){");  
    echo("  TypingHandler.handleTypingInUserDataTextArea(".$content->{'m_sId'}.", e);");
    echo(" });");    

    echo("</script>");

}            

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

雪若未夕 2024-11-14 06:35:56

首先,对于奇数和偶数样式,不需要类只需使用 css

这里是信息 然后在

php 中只在一行中回显您需要的内容

$count = count($contentArray);
for($i = 0; $i < $count; $i++){  
    $content = $contentArray[$i];    
    echo('<li><textarea class="userdata" id="user_data_textarea_"'.$content->{'m_sId'}.'">'.$content->{'m_sDataContent'}.'</textarea></li>');   
}

,然后将 jquery 放在远离 php 的 html 页面中,

我们可以通过使用 以选择器开头

$('[id^=user_data_textarea_]').bind('keydown', function(e){  
    var id = this.id.str_replace("user_data_textarea","");
    TypingHandler.handleTypingInUserDataTextArea(id, e);
});    

first for your odd and even styling there is not need for a class just use css

here is info on that

then in php only echo what you need in one line

$count = count($contentArray);
for($i = 0; $i < $count; $i++){  
    $content = $contentArray[$i];    
    echo('<li><textarea class="userdata" id="user_data_textarea_"'.$content->{'m_sId'}.'">'.$content->{'m_sDataContent'}.'</textarea></li>');   
}

and lets put the jquery in the html page away from php

we get can get every item by using starts with selector

$('[id^=user_data_textarea_]').bind('keydown', function(e){  
    var id = this.id.str_replace("user_data_textarea","");
    TypingHandler.handleTypingInUserDataTextArea(id, e);
});    
Smile简单爱 2024-11-14 06:35:56

关于“for”循环的一个技巧是,您应该在循环之前计算 $contentArray 的计数。每次执行循环时,都必须调用该函数。

$count = count($contentArray);

for ($i=0; $i<count; $i++) {
// ...
}

One tip on your "for" loop, you should calculate the count of $contentArray before the loop. Every time the loop executes, it has to call that function.

$count = count($contentArray);

for ($i=0; $i<count; $i++) {
// ...
}
尽揽少女心 2024-11-14 06:35:56

你可以尝试真正的 HTML:

<?php
for($i = 0; $i < count($contentArray); $i++){  
  $rowClass = $i %2 == 0 ?'even_row' : 'odd_row';
?>
    <li class='<?= $rowClass ?>'>
      <textarea class='userdata' id='user_data_textarea_<?=$content->{'m_sId'}?>'>
        <?= $content->{'m_sDataContent'} ?>
      </textarea>
    </li>
    <script type='text/javascript'>
    //etc...
    </script>
<?php } ?>

You could try real HTML:

<?php
for($i = 0; $i < count($contentArray); $i++){  
  $rowClass = $i %2 == 0 ?'even_row' : 'odd_row';
?>
    <li class='<?= $rowClass ?>'>
      <textarea class='userdata' id='user_data_textarea_<?=$content->{'m_sId'}?>'>
        <?= $content->{'m_sDataContent'} ?>
      </textarea>
    </li>
    <script type='text/javascript'>
    //etc...
    </script>
<?php } ?>
白色秋天 2024-11-14 06:35:56

它应该看起来像这样,以便在 IDE 中具有更好的可读性。

<?php
foreach($contentArray as $content){
    ?>
    <li>
        <textarea class="userdata" id="user_data_textarea<?php echo htmlentities($content['m_sId']); ?>">
            <?php echo htmlspecialchars($content['m_sDataContent']); ?>
        </textarea>
        <script type="text/javascript">
            $('#user_data_textarea_<?php echo htmlspecialchars($content['m_sId']); ?>').bind('keydown',function(e){
                TypingHandler.handleTypingInUserDataTextArea('<?php echo htmlspecialchars($content['m_sId']); ?>',e);
            });
        </script>
    </li>
<?php
}

It should look something like this, for better readability in the IDE.

<?php
foreach($contentArray as $content){
    ?>
    <li>
        <textarea class="userdata" id="user_data_textarea<?php echo htmlentities($content['m_sId']); ?>">
            <?php echo htmlspecialchars($content['m_sDataContent']); ?>
        </textarea>
        <script type="text/javascript">
            $('#user_data_textarea_<?php echo htmlspecialchars($content['m_sId']); ?>').bind('keydown',function(e){
                TypingHandler.handleTypingInUserDataTextArea('<?php echo htmlspecialchars($content['m_sId']); ?>',e);
            });
        </script>
    </li>
<?php
}
挽清梦 2024-11-14 06:35:56

您可以从 echo 语句中删除 ( ),它们不一定需要,并且可能有助于使其看起来更整洁......

You could remove the ( ) from the echo statements, they're not necessarily needed and might help make it look a little neater...

刘备忘录 2024-11-14 06:35:56

这对我来说实际上看起来很容易理解;我可以毫无困难地弄清楚你在做什么。我建议的唯一区别是使用 三元运算符对于行类:

echo "<li class='".( ($i%2 == 0) ? "even" : "odd" )."_row'>";

...但这只是我的情况,有些人会发现这更令人困惑,而不是更少。我个人喜欢将所有内容放在一行中。

That actually looks pretty understandable to me; I could figure out what you're doing without difficulty. The only difference I would suggest would be the use of ternary operators for the row class:

echo "<li class='".( ($i%2 == 0) ? "even" : "odd" )."_row'>";

...but that's just me, some would find that MORE confusing, rather than less. I personally like putting it all in one line.

扶醉桌前 2024-11-14 06:35:56

就我个人而言,我喜欢使用 printf 在 php 中编写 html 代码。它可能看起来像:

for($i = 0; $i < count($contentArray); $i++){  

    printf("<li class='%s'>", $i % 2 ? "odd_row" : "even_row"); 
    $content = $contentArray[$i];    

    printf("<textarea class='userdata' id='user_data_textarea_%s'>%s</textarea>",
        $content->{'m_sId'},
        $content->{'m_sDataContent'});

    echo("</li>");   

    echo("<script type='text/javascript'>");

    printf("$('#user_data_textarea_%1$s').bind('keydown', function(e){
        TypingHandler.handleTypingInUserDataTextArea(%1$s, e);
         });",
        $content->{'m_sId'});     

    echo("</script>");

}    

Personnaly, I like to use printf to write html code in php. It could look like:

for($i = 0; $i < count($contentArray); $i++){  

    printf("<li class='%s'>", $i % 2 ? "odd_row" : "even_row"); 
    $content = $contentArray[$i];    

    printf("<textarea class='userdata' id='user_data_textarea_%s'>%s</textarea>",
        $content->{'m_sId'},
        $content->{'m_sDataContent'});

    echo("</li>");   

    echo("<script type='text/javascript'>");

    printf("$('#user_data_textarea_%1$s').bind('keydown', function(e){
        TypingHandler.handleTypingInUserDataTextArea(%1$s, e);
         });",
        $content->{'m_sId'});     

    echo("</script>");

}    
葬﹪忆之殇 2024-11-14 06:35:56
<?php
    foreach($contentArray as $content){
        $class = ($i %2 == 0) ? "even_row": "odd_row"; ?>
        <li class="<?php echo $class ?>">
            <textarea class='userdata' id='user_data_textarea_<? echo $content['m_sId'] ?>'>
                <? php echo $content['m_sDataContent'] ?>
            </textarea>
        </li>
        <script type='text/javascript'>
            $('#user_data_textarea_<?php echo content['m_sId'] ?>').bind('keydown', function(e){
                TypingHandler.handleTypingInUserDataTextArea(<?php $content['m_sId'] ?>, e);
            });
        </script>
<?php } // end foreach ?>
<?php
    foreach($contentArray as $content){
        $class = ($i %2 == 0) ? "even_row": "odd_row"; ?>
        <li class="<?php echo $class ?>">
            <textarea class='userdata' id='user_data_textarea_<? echo $content['m_sId'] ?>'>
                <? php echo $content['m_sDataContent'] ?>
            </textarea>
        </li>
        <script type='text/javascript'>
            $('#user_data_textarea_<?php echo content['m_sId'] ?>').bind('keydown', function(e){
                TypingHandler.handleTypingInUserDataTextArea(<?php $content['m_sId'] ?>, e);
            });
        </script>
<?php } // end foreach ?>
御弟哥哥 2024-11-14 06:35:56

jQuery 代码应该已经在 HTML 中,使用一些主选择器而不是一一绑定元素,这对我来说没有意义。这应该可以澄清你的代码。

for($i = 0; $i < count($contentArray); $i++){  
    $content = $contentArray[$i];    

    echo "<li class='" . (($i %2 == 0) ? "even_row" : "odd_row") . ">";
        echo "<textarea class='userdata' id='user_data_textarea_".$content->{'m_sId'}."'>";
        echo $content->{'m_sDataContent'};  
        echo "</textarea>"; 
    echo "</li>";   
}      

添加

一般情况:

$(function() {
    $('.userdata').click(function() {
        some_function($(this).attr('id');
    });
})

即使用类选择器进行绑定,并稍后使用一些唯一标识符来完成这项工作。

jQuery code should be already in the HTML, using some main selector and not binding elements one by one, it not makes sense for me. That should clarify your code.

for($i = 0; $i < count($contentArray); $i++){  
    $content = $contentArray[$i];    

    echo "<li class='" . (($i %2 == 0) ? "even_row" : "odd_row") . ">";
        echo "<textarea class='userdata' id='user_data_textarea_".$content->{'m_sId'}."'>";
        echo $content->{'m_sDataContent'};  
        echo "</textarea>"; 
    echo "</li>";   
}      

ADDED

A generic case:

$(function() {
    $('.userdata').click(function() {
        some_function($(this).attr('id');
    });
})

That is, bind using a class selector and late use some unique identifier for doing the job.

萌逼全场 2024-11-14 06:35:56

将所有内容放入数组中,然后在循环末尾回显它们。

// Put each item in the array, then echo at the end
$items = array();
$js = array();

// I'm assuming that your content array has numeric keys
// if not, use the for statement from your original code
foreach ($contentArray as $i => $content) 
{
    // using sprintf
    $items[] = sprintf('<li class="%s_row"><textarea class="userdata" id="user_data_textarea_%s">%s</textarea></li>'
        , ($i % 2) ? 'even' : 'odd'
        , $content->m_sId
        , $content->m_sDataContent
    );

    // or just plain old concatenation
    $js[] = "$('#user_data_textarea_{$content->m_sId}').bind('keydown', function(e){TypingHandler.handleTypingInUserDataTextArea({$content->m_sId}, e);});";
}

echo "<ul>" . join("\n", $items) . "</ul>\n"
    . '<script type="text/javascript">' . join("\n", $js) . "</script>\n";

Put everything in arrays, then echo them at the END of your loop.

// Put each item in the array, then echo at the end
$items = array();
$js = array();

// I'm assuming that your content array has numeric keys
// if not, use the for statement from your original code
foreach ($contentArray as $i => $content) 
{
    // using sprintf
    $items[] = sprintf('<li class="%s_row"><textarea class="userdata" id="user_data_textarea_%s">%s</textarea></li>'
        , ($i % 2) ? 'even' : 'odd'
        , $content->m_sId
        , $content->m_sDataContent
    );

    // or just plain old concatenation
    $js[] = "$('#user_data_textarea_{$content->m_sId}').bind('keydown', function(e){TypingHandler.handleTypingInUserDataTextArea({$content->m_sId}, e);});";
}

echo "<ul>" . join("\n", $items) . "</ul>\n"
    . '<script type="text/javascript">' . join("\n", $js) . "</script>\n";
最单纯的乌龟 2024-11-14 06:35:56

使用例如 smarty 分隔您的内容和代码。它在短期内需要一些基础设施投资,但从长远来看可以改善维护。

考虑到这些评论,让我们将 PHP 视为真正的模板语言。

$contentCount = count($contentArray);
for($i = 0; $i < $contentCount; $i++)
{
    $rowType = ( $i % 2 ) ? 'even' : 'odd';
    $content = $contentArray[$i];
    echo <<<EOT
<li class='{$rowType}_row'>
    <textarea class='userdata' id='user_data_textarea_{$content->m_sId}'>
        {$content->m_sDataContent}
    </textarea>

</li>
<script type="text/javascript">
    $('#user_data_textarea_{$content->m_sId}').bind('keydown', function(e)
    {
        TypingHandler.handleTypingInUserDataTextArea({$content->m_sId}, e);
    }
</script>
EOT;
}

Separate your content and code using for example smarty. It requires some infrastructure investment in the short term, but improves maintenance in the long run.

Reflecting the comments, let's then treat PHP as a real templating language.

$contentCount = count($contentArray);
for($i = 0; $i < $contentCount; $i++)
{
    $rowType = ( $i % 2 ) ? 'even' : 'odd';
    $content = $contentArray[$i];
    echo <<<EOT
<li class='{$rowType}_row'>
    <textarea class='userdata' id='user_data_textarea_{$content->m_sId}'>
        {$content->m_sDataContent}
    </textarea>

</li>
<script type="text/javascript">
    $('#user_data_textarea_{$content->m_sId}').bind('keydown', function(e)
    {
        TypingHandler.handleTypingInUserDataTextArea({$content->m_sId}, e);
    }
</script>
EOT;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文