Javascript 函数在一个页面上运行,但在包含在主页上时不起作用

标签 javascript php html

我对使用 javascript 比较陌生,在与 php 一起使用时遇到了问题。

我正在创建一个预算计算器,允许用户从菜单中选择项目(例如电影票)。我创建了一个数据库,其中包含常见商品及其相关价格的列表,并使用 php 将这些信息传递到我的网站中。

我在网上发现了一个 JavaScript 函数,可以在用户选择更多项目时对用户的总花费进行小计。因此,当用户选择项目旁边的复选框时,页面底部的小计会自动更新。

为了确保安全,我正在运行 php 查询,该查询在单独的页面上打印出信息,并使用 include() 函数将其包含在主页上。

我遇到的问题是,当我运行仅包含 php 代码的页面并在此页面上包含 javscript 函数时,它可以正常工作,但是,当它包含在主页上时,它将无法工作。

这是我正在使用的小计表单版本的演示 - https://www.dyn-web.com/tutorials/forms/checkbox/group.php

//html

<html>
   <!-- submenu for transport-->
<button class="collapsible">Transport</button>
  <div class="content" >
    <!-- further submenu for public transport -->
            <button class="collapsible" > Public Transport</button>
     <div class="content">
        <table class="auto-style2" style="width: 96%">
        <tbody class="auto-style2">     
         <tr>
               <td style="width: 353px; height: 26px;">&nbsp;</td>
           <td style="height: 26px">
           <div class ='row1'>€</div></td>
         </tr>
            <?php
               include('publictransport.php');
             ?> 

        </tbody>        
        </table>
    </div>  
</html>    

//php

<?php
//This is publictransport.php
//establish connection
include('detail.php');
##query information
$q  = 'SELECT name,price FROM expenditure WHERE sub_category = "public_transport"';
$result = $db->query($q);
$num_results = mysqli_num_rows($result);
echo "<form action='' method='post' class='demoForm' id='demoForm'><div id = 'transport'>";
while($row = mysqli_fetch_row($result))
{
    //loop and print out information in html format
    echo "<tr>";
    echo "<td class = 'firstcolumn'>", $row[0] ,"</td>";  
    echo "<td class = 'row1'>",  $row[1],"</td>";
    echo "<td class ='row1'> <div id='ck-button'> <label> <input type='checkbox'";
    echo "value = '". $row[1]."'><span> + </span></label></div></td></tr>";
}

echo "</div><p><label>Total: $ <input type='text' name='total' class='num' size='6' value='0' readonly='readonly'/></label></p>";
echo "</form>";
?>

//javascript

<script>
// call onload or in script segment below form
function attachCheckboxHandlers() {
// get reference to element containing transport checkboxes
var el = document.getElementById('transport');
// get reference to input elements in transport container element
var types = el.getElementsByTagName('input');

// assign updateTotal function to onclick property of each checkbox
for (var i=0, len=types.length; i<len; i++) {
    if ( types[i].type === 'checkbox' ) {
        types[i].onclick = updateTotal;
    }
 }

}

// called onclick of transport checkboxes

function updateTotal(e) {

// 'this' is reference to checkbox clicked on

var form = this.form;

// get current value in total text box, using parseFloat since it is a 
string

var val = parseFloat( form.elements['total'].value );

// if check box is checked, add its value to val, otherwise subtract it

if ( this.checked ) {
    val += parseFloat(this.value);
} else {
    val -= parseFloat(this.value);
}

// format val with correct number of decimal places
// and use it to update value of total text box

form.elements['total'].value = formatDecimal(val);
}

// format val to n number of decimal places
// modified version of Danny Goodman's (JS Bible)

function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
while (str.length <= n) {
    str = "0" + str;
}
var pt = str.length - n;
return str.slice(0,pt) + "." + str.slice(pt);
}

// in script segment below form

attachCheckboxHandlers();

</script>

问题是在主页上,JavaScript 无法找到复选框。值“types”是一个复选框数组,长度应为 4。在 publictransport.php 页面上,它的长度为 4,而在主页上,它返回一个空数组。

任何帮助将非常感激,因为我是 javascript 的新手,我可能没有以最好的方式解释这个问题!

最佳答案

<div> <tbody> 内不允许使用标签,因此呈现的 HTML 与预期的不同。

这就是 Firefox 65 呈现 HTML 的方式 enter image description here

请注意,Firefox 完全忽略了 <form><div>标签,并放置 <tr> 2 位家长。

修补此问题的最简单方法是删除 <form><div>完全标记,只需放置 id = 'transport'关于<tr> ,这样 JS 就应该可以工作了。

如果您需要表单,则应该这样放置

<html>
   <!-- submenu for transport-->
<button class="collapsible">Transport</button>
  <div class="content" >
    <!-- further submenu for public transport -->
            <button class="collapsible" > Public Transport</button>
     <div class="content">
        <table class="auto-style2" style="width: 96%">
        <tbody class="auto-style2">     
         <tr>
               <td style="width: 353px; height: 26px;">&nbsp;</td>
           <td style="height: 26px">
           <div class ='row1'>€</div></td>
         </tr>
         <tr>
           <td>
            <?php
               include('publictransport.php');
             ?> 
           </td>
         </tr>
        </tbody>        
        </table>
    </div>  
</html>  

还有publictransport.php添加<table>里面<div id='transport'>

关于Javascript 函数在一个页面上运行,但在包含在主页上时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54484386/

相关文章:

javascript - setTimeout 后返回变量

php - Laravel 如何在生产环境中启动服务器

java - 使用 Selenium 在影子 DOM 中查找元素

javascript - 如何在 Redux 中使用 React Native AsyncStorage?

javascript - Angular 移动不精确

javascript - 为什么 Angular 项目不能像其他 JavaScript 项目一样在浏览器上运行

php - 学说 2.0 Bootstrap ?

php - PDO:获取结果时去除斜线

Jquery 树列表

Javascript 函数不随 html onclick 触发