【问题标题】:Remove last empty line from select field with "for" loop wordpress使用“for”循环wordpress从选择字段中删除最后一个空行
【发布时间】:2020-07-13 07:37:57
【问题描述】:

我在 WordPress 中创建了一个自定义小部件,在小部件中我尝试使用 for 循环创建一个选择字段,并在其中显示从 1 到 10 的 10 个数字。

我在 10 号下创建了但它有一个空行。

你能帮我删除那个空行吗?

<label for="<?php echo $this->get_field_id('text'); ?>">
<select width="50" style="width: 50px"  class='widefat' id=" <?php $this->get_field_id('timet8t2'); ?>" name="<?php $this->get_field_name('timet8t2'); ?>" type="text">

<?php 
    for($i=1; $i<11; $i++)
    {

        echo "<option value=".$i.">"."$i<br>"."</option>";
    }
?> 


    <option name="<?php $this->get_field_name('timet8t2'); ?>"> </option> 
  </select> 
</label>

【问题讨论】:

  • $this-&gt;get_field_name('timet8t2')生成的选项没有标签。

标签: php wordpress for-loop select


【解决方案1】:

第 1 部分

您需要删除最后一个选项:

<option name="<?php $this->get_field_name('timet8t2'); ?>"><?= $this->get_field_name('timet8t2'); ?></option>

第 2 部分

要显示带有前导 0 的选项标签,您可以使用 sprintf()

见下文:

<label for="<?php echo $this->get_field_id('timet8t2'); ?>">
    <select width="50" style="width: 50px"  class='widefat' id=" <?php $this->get_field_id('timet8t2'); ?>" name="<?php $this->get_field_name('timet8t2'); ?>" type="text">

<?php 
    for($i=1; $i<11; $i++)
    {
        echo "<option value=".$i.">". sprintf("%'.02d", $i) . "</option>";
    }
?> 
  </select> 
</label>

Simplified PHPSandbox

【讨论】:

  • 你好 segFault,它有效。 10号下面的空行,完全去掉了!请您告诉我如何将数字 1、2、3、... 更改为 01、02、03... ?谢谢! :)
  • 看看sprintf,具体是:echo sprintf("%'.02d\n", $i);也可以用printf()
  • 好的,我很抱歉.. 在选择字段中,我想显示从 1 到 24 的数字,并且它显示的数字像“01,02,03,04,05,06,07,08, 09、10、11、12、13、14、15、16、17、18、19、20、21、22、23、24"
  • 是的,无论选项有多少,您都可以使用这些功能中的任何一个...我可以更新我的答案为您做这件事 np
  • 它有效!!!! segFault,我不知道该怎么说谢谢。你太棒了!!!我希望有一天我能回报我的帮助!它显示像“ 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, ...但在站点(前端)显示“ 1, 2 , 3, 4, 5, 6, 7, 8, 9, 10 ,11, ...”。我认为现在还可以,再次非常感谢!
猜你喜欢
  • 2021-12-13
  • 2013-06-26
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多