如何在 PHP 中按父类名获取元素


How to get element by parent classname in PHP

HTML 标记:

<form>
  <div class="required">
    <input id="name" name="name">
  </div>
  <div class="required">
    <input id="email" name="email">
  </div>
  <div class="non-required">
    <input id="other" name="other">
  </div>
  ...
  alot of input here
  ...
</form>

.PHP:

<?php
extract($_POST, EXTR_PREFIX_ALL, 'input');
if (empty($input_name) || empty($input_email) || empty($input_other) || ... alot of input here...) { // i want only the input that has `required` class in this line
  // main function here
}
?>

我可以手动编辑它,但是如何自动选择具有 PHP 主函数类required input

谢谢。

无法访问父级的类名。当用户提交表单时,不会传输此信息。

$_POST 中唯一可用的信息是输入元素的名称和值。您可以定义输入元素的名称来表示必需/非必需,如下所示:

<form>
    <div class="required">
         <input id="name" name="required[name]">
    </div>
    <div class="required">
         <input id="email" name="required[email]">
    </div>
    <div class="optional">
         <input id="another" name="optional[another]">
    </div>
    <div class="required">
         <input id="other" name="required[other]">
    </div>
</form>

使用此架构,您将在 $_POST 中有两个子数组,分别命名为 required 和 optional:

Array //$_POST
(
     [required] => Array
     (
         [name] => value,
         [email] => value,
         [name] => value
     ),
     [optional] => Array
     (
         [another] => value
     )
)

警告
如果您使用此解决方案,请确保您正确验证了输入。您将信任用户代理提供有关字段的正确信息。看看Trincot对纯服务器端解决方案的回答。

由于您自己生成 HTML,因此您实际上知道哪些输入元素具有"必需"类。因此,我建议您首先创建一个包含必填字段的数组,然后使用动态类值从中生成 HTML。

然后稍后你可以使用相同的数组来检查空性:

网页生成:

<?php
// define the list of required inputs:
$required = array("name", "email");
// define a function that returns "required" or "non-required" 
// based on the above array.
function req($name) {
    global $required;
    return in_array($required, $name) ? 'required' : 'non-required';
}
// Now generate the classes dynamically, based on the above:
?>
<form>
  <div class="<?=req('name')?>">
    <input id="name" name="name">
  </div>
  <div class="<?=req('email')?>">
    <input id="email" name="email">
  </div>
  <div class="<?=req('other')?>">
    <input id="other" name="other">
  </div>
  ...
  alot of input here
  ...
</form> 

然后在处理输入时,再次使用上述函数:

<?php
// This extract is not needed for the next loop, but you might need it still:
extract($_POST, EXTR_PREFIX_ALL, 'input');
// go through all inputs that are required and test for empty
// until you find one, and produce the appropriate response 
foreach($required as $name) {
    if (empty($_POST[$name])) {
        // main (error?) function here
        break; // no need to continue the loop as we already found an empty one
    }
}
?>