首页 > 解决方案 > JavaScript:getElementById() 不工作(使用以前访问数据库的表或段落)

问题描述

我遇到了一个问题,我想检索一个 html 元素以在 javascript 中使用。我正在尝试使用函数 getElementById(),whick 确实/确实可以使用另一个元素(通过单击图片将物品放置在其中的购物车),但不适用于我目前正在处理的元素(表(或者在我放弃那一段之后)通过“数据-”属性(例如数据价格)保存一些信息(这样就不必通过json等传递/访问这些信息)。
我总是得到错误,即我将获取的元素分配给的变量为空(“TypeError:datentabelle 为空”)。

这是名为“MyJS.js”的完整 .js 文件:

function addpizza( pizzanummer, pizzaname, preis) {
"use strict";
    var warenkorb = document.getElementById("warenkorb");
    var opt = document.createElement('option');
    opt.value = pizzanummer;
    opt.label = pizzaname;
    //opt.data-datapreis = preis;
    warenkorb.appendChild(opt);
    var para = document.getElementById("paragraphid");
    let bisherpreis = para.textContent;
    let neupreis = parseFloat(bisherpreis) + parseFloat(preis);
    var opt = document.createElement('option');
    para.textContent = neupreis.toFixed(2);

    var datentabelle = document.getElementById(0);     !!This is were the assignment is supposed to happen!!
    var aktpreis = datentabelle.data-preis;            !!This is were the error is thrown (when "datentabelle" is first accessed)!!
    //calc();
}


/*
function calc(){
    //no useable body currently
}
*/

这是 HTML 元素代码/构造的摘录

        foreach($dbergebnisse as $pizza){
            $aktpizzanummer = $pizza["PizzaNummer"];
            $aktname     = $pizza["PizzaName"];
            $aktpreis    = $pizza["Preis"];
            $aktbilddatei  = $pizza["Bilddatei"];
echo <<< test10
        <p id=$aktpizzanummer data-preis=$aktpreis> idptemp </p>
        <p>$aktname</p>
        <p>$aktpreis €&lt;/p>
        <img src=$aktbilddatei alt="margherita" width="80" height="80" onclick="addpizza($aktpizzanummer,'$aktname',$aktpreis)">
test10;

如果相关,这是相应的完整 .php 文件:

<?php   // UTF-8 marker äöüÄÖÜ߀
/**
 * Class PageTemplate for the exercises of the EWA lecture
 * Demonstrates use of PHP including class and OO.
 * Implements Zend coding standards.
 * Generate documentation with Doxygen or phpdoc
 * 
 * PHP Version 5
 *
 * @category File
 * @package  Pizzaservice
 * @author   Bernhard Kreling, <b.kreling@fbi.h-da.de> 
 * @author   Ralf Hahn, <ralf.hahn@h-da.de> 
 * @license  http://www.h-da.de  none 
 * @Release  1.2 
 * @link     http://www.fbi.h-da.de 
 */

// to do: change name 'PageTemplate' throughout this file
require_once './Page.php';

/**
 * This is a template for top level classes, which represent 
 * a complete web page and which are called directly by the user.
 * Usually there will only be a single instance of such a class. 
 * The name of the template is supposed
 * to be replaced by the name of the specific HTML page e.g. baker.
 * The order of methods might correspond to the order of thinking 
 * during implementation.

 * @author   Bernhard Kreling, <b.kreling@fbi.h-da.de> 
 * @author   Ralf Hahn, <ralf.hahn@h-da.de> 
 */
class Bestellung extends Page
{

    // to do: declare reference variables for members 
    // representing substructures/blocks

    /**
     * Instantiates members (to be defined above).   
     * Calls the constructor of the parent i.e. page class.
     * So the database connection is established.
     *
     * @return none
     */
    protected function __construct() 
    {
        parent::__construct();
        // to do: instantiate members representing substructures/blocks
    }

    /**
     * Cleans up what ever is needed.   
     * Calls the destructor of the parent i.e. page class.
     * So the database connection is closed.
     *
     * @return none
     */
    protected function __destruct() 
    {
        parent::__destruct();
    }

    /**
     * Fetch all data that is necessary for later output.
     * Data is stored in an easily accessible way e.g. as associative array.
     *
     * @return none
     */
    protected function getViewData()
    {
        // to do: fetch data for this view from the database
        $angebot = array();

        $SQLabfrage = "SELECT * FROM angebot";
        $Recordset = $this->_database  ->query ($SQLabfrage);//$Recordset = $this->_database  ->query ($SQLabfrage);        //wird hier jetzt iwie einfach ein recordset deklariert (ohne klasse usw?)

        if (!$Recordset)
            throw new Exception("Query failed: ".$Connection->error);

        //return $Recordset;


        $counter = 0;
        $pizza = array();                   //konnte man iwie net drinnen definieren??
        while ($record = $Recordset->fetch_assoc()){
            $pizza["PizzaNummer"] = $record["PizzaNummer"];
            $pizza["PizzaName"]   = $record["PizzaName"];
            $pizza["Preis"]       = $record["Preis"];
            $pizza["Bilddatei"]   = $record["Bilddatei"];
            //$angebot[0] = $pizza;
            array_push($angebot, $pizza);
        }

        return $angebot;
    }






    /**
     * First the necessary data is fetched and then the HTML is 
     * assembled for output. i.e. the header is generated, the content
     * of the page ("view") is inserted and -if avaialable- the content of 
     * all views contained is generated.
     * Finally the footer is added.
     *
     * @return none
     */
    protected function generateView()                   //warum geht $record (in schleife) benutzen hier nicht, aber in getviewdata schon??
    {

        $dbergebnisse = $this->getViewData();
        //$record = $this->$Recordset;
        //$aktnummer = $record["PizzaNummer"];
        $this->generatePageHeader('Bestellung');
        // to do: call generateView() for all members
            //<form action="https://echo.fbi.h-da.de/" method="POST">   
            //<form action="http://127.0.0.1/pizzaservice/Kundeerbend.php" method="POST">   //original

        //$_SESSION["testwert"] = "bla";
        //<form action="http://127.0.0.1/pizzaservice/Kundeerbend.php" method="POST">   
    echo <<< test1
        <body>

        <form action="http://127.0.0.1/pizzaservice/ewa/Kundeerbend.php" method="POST">     

        <h2> Bestellung</h2>
        <h2> Speisekarte</h2>
test1;

        foreach($dbergebnisse as $pizza){
            $aktpizzanummer = $pizza["PizzaNummer"];
            $aktname      = $pizza["PizzaName"];
            $aktpreis     = $pizza["Preis"];
            $aktbilddatei  = $pizza["Bilddatei"];
echo <<< test10
        <p id=$aktpizzanummer data-preis=$aktpreis> idptemp </p>
        <p>$aktname</p>
        <p>$aktpreis €&lt;/p>
        <img src=$aktbilddatei alt="margherita" width="80" height="80" onclick="addpizza($aktpizzanummer,'$aktname',$aktpreis)">
test10;

        }

/*      
        echo <<< test1
        <body>
    <form action="http://127.0.0.1/pizzaservice/Kundeerbend.php" method="POST">
    <h2> Bestellung</h2>
    <h2> Speisekarte</h2>
*/  
/*

    <!-- Pizzen aus Datenbank -->
    <img src="ewabild.jpg" alt="margherita" width="80" height="80">
    <p>Margherita</p>
    <p>4.00€&lt;/p>
    <img src="ewabild.jpg" alt="salami" width="80" height="80">
    <p>Salami</p>
    <p>4.50€&lt;/p>
    <img src="ewabild.jpg" alt="hawaii" width="80" height="80">
    <p>Hawaii</p>
    <p>5.50€&lt;/p>
*/  
        $angebotsgroesse = count($dbergebnisse);            //kein code in ausgabe!! (also nicht nach echo)
echo <<< test1
    <h2>Warenkorb</h2>


    <select name="top[]" id= "warenkorb" size=" $angebotsgroesse " multiple>
test1;

foreach($dbergebnisse as $pizza){
            $aktpizzanummer = $pizza["PizzaNummer"];
            $aktname      = $pizza["PizzaName"];
            $aktpreis     = $pizza["Preis"];
            $aktbilddatei  = $pizza["Bilddatei"];

echo <<< test1
            <option value = "$aktpizzanummer"> $aktname </option>
test1;
}
echo "</select>";













/*
echo <<< test2
<table name = "blatabelle" id="infoetc" size=" $angebotsgroesse " multiple>
<tr>
    <td>"bla</td>
</tr>
test2;


foreach($dbergebnisse as $pizza){
            $aktpizzanummer = $pizza["PizzaNummer"];
            $aktname      = $pizza["PizzaName"];
            $aktpreis     = $pizza["Preis"];
            $aktbilddatei  = $pizza["Bilddatei"];

echo <<< test1
            <tr id = "$aktpizzanummer">
                <td data-name>$aktname</td>
                <td data-preis>$aktpreis</td>
            </tr>
test1;
}

echo "</table>";
*/



echo <<< test1
    <p id="paragraphid">0</p>
    <input type="hidden" name="gesamtpreis" value="14.50" />
    <p><label>
        <input type="text" name="Zuname" placeholder="Ihr Nachname"/>
        </label></p>
    <p><label>
        <input type="text" name="kundenadresse" placeholder="Ihre Adresse"/>
        </label></p>
    <input type="reset" name="Alle löschen" value="Alle Löschen" />
    <input type="button" name="Auswahl löschen" value="Auswahl Löschen" />
    <input type="submit" name="bestellen" value="Bestellen"  />
    </form>
    <script type ="text/javascript" src="MyJS.js"></script>
</body>
test1;
        // to do: output view of this page
        $this->generatePageFooter();
    }

    /**
     * Processes the data that comes via GET or POST i.e. CGI.
     * If this page is supposed to do something with submitted
     * data do it here. 
     * If the page contains blocks, delegate processing of the 
     * respective subsets of data to them.
     *
     * @return none 
     */
    protected function processReceivedData() 
    {
        parent::processReceivedData();
        // to do: call processReceivedData() for all members

    }

    /**
     * This main-function has the only purpose to create an instance 
     * of the class and to get all the things going.
     * I.e. the operations of the class are called to produce
     * the output of the HTML-file.
     * The name "main" is no keyword for php. It is just used to
     * indicate that function as the central starting point.
     * To make it simpler this is a static function. That is you can simply
     * call it without first creating an instance of the class.
     *
     * @return none 
     */    
    public static function main() 
    {
        //session_start();
        try {
            $page = new Bestellung();
            $page->processReceivedData();

            $page->generateView();
        }
        catch (Exception $e) {
            header("Content-type: text/plain; charset=UTF-8");
            echo $e->getMessage();
        }
    }
}

// This call is starting the creation of the page. 
// That is input is processed and output is created.
Bestellung::main();

// Zend standard does not like closing php-tag!
// PHP doesn't require the closing tag (it is assumed when the file ends). 
// Not specifying the closing ? >  helps to prevent accidents 
// like additional whitespace which will cause session 
// initialization to fail ("headers already sent"). 
//? >

谢谢你的帮助

标签: javascriptphphtmldomgetelementbyid

解决方案


你应该参考data-preisvia dataset

你的代码会是这样的:

function addPizza() {
     /* Your logic */
    var datentabelle = document.getElementById(0); 
    var aktpreis = datentabelle.dataset.preis;    

}        

推荐阅读