jQuery:.append 或 .appendTo PHP 到 HTML 标记中的元素

jQuery: .append or .appendTo PHP to an element within an HTML tag?

本文关键字:元素 HTML append appendTo PHP jQuery      更新时间:2023-09-26

我正在尝试学习减少我编写的代码量的技术。我有一个相当长的表单,我使用 PHP 填充。我想知道是否可以在 HTML 标签中附加 PHP。

例如,与其写这个:

<div id="title">Referrals</div>
        <input type="hidden" name="REFERRALS" value="n"/>
        <input id="wref" type="radio" name="REFERRALS" value='w' <?php echo ($REFERRALS == 'w') ? "checked='checked'" : "" ; ?> />        
            <label for="wref"></label>
        <input id="pref" type="radio" name="REFERRALS" value='p' <?php echo ($REFERRALS == 'p') ? "checked='checked'" : "" ; ?> /> 
            <label for="pref"></label>  
        <input id="cref" type="radio" name="REFERRALS" value='c' <?php echo ($REFERRALS == 'c') ? "checked='checked'" : "" ; ?> /> 
            <label for="cref"></label>
        <hr noshade></hr> 
 <div id="title">Laundry</div>
        <input type="hidden" name="LAUNDRY" value="n"/>
        <input id="wlaundry" type="radio" name="LAUNDRY" value='w' <?php echo ($LAUNDRY == 'w') ? "checked='checked'" : "" ; ?> />        
            <label for="wlaundry"></label>
        <input id="plaundry" type="radio" name="LAUNDRY" value='p' <?php echo ($LAUNDRY == 'p') ? "checked='checked'" : "" ; ?> /> 
            <label for="plaundry"></label>  
        <input id="claundry" type="radio" name="LAUNDRY" value='c' <?php echo ($LAUNDRY == 'c') ? "checked='checked'" : "" ; ?> /> 
            <label for="claundry"></label>
        <hr noshade></hr>           
 <div id="title">Shower</div>
        <input type="hidden" name="SHOWER" value="n"/>
        <input id="wshower" type="radio" name="SHOWER" value='w' <?php echo ($SHOWER == 'w') ? "checked='checked'" : "" ; ?> />       
            <label for="wshower"></label>
        <input id="pshower" type="radio" name="SHOWER" value='p' <?php echo ($SHOWER == 'p') ? "checked='checked'" : "" ; ?> /> 
            <label for="pshower"></label>   
        <input id="cshower" type="radio" name="SHOWER" value='c' <?php echo ($SHOWER == 'c') ? "checked='checked'" : "" ; ?> /> 
            <label for="cshower"></label>
        <hr noshade></hr> 

我想使用一个jQuery语句,例如...

variableName = $("input[name*='value']").val();
$('input[value^=']').append(<?php echo (variableName == 'c') ? "checked='checked'" : "" ; ?>);

将 PHP 附加到每个相关的 HTML 标记中。

但是,我不知道这是否可能,并且尚未在jQuery api中找到任何解决方案。

你不能使用 JavaScript(jQuery 是一个 JavaScript 库(以这种方式与 PHP 交互。

PHP 在服务器上解析,生成的 HTML 被发送到您的浏览器进行渲染。

您可以使用JavaScript(和/或jQuery(与浏览器接收的HTML进行交互,但随后将失去持久化数据的能力,例如在表单提交之后,而不涉及服务器或某种客户端存储。