呈现的HTML页面不会将事件处理程序加载到所有元素

时间:2018-01-06 09:22:57

标签: jquery node.js firebase express ejs

我目前正在开发一个项目,该项目由nodejs + express中的Web服务器应用程序和一些使用ejs呈现的客户端视图组成。在我的主app.js中,我们有以下内容:

const express = require('express');
const path = require('path');
const app = express();
const firebase = require('firebase');
const bodyParser = require('body-parser');
var methodOverride = require('method-override');

const config = {
    apiKey: "AIzaSyC4g2YjCJ9uF5Ea8loYXVm7xinpumjRlfI",
    authDomain: "tic-project-46906.firebaseapp.com",
    databaseURL: "https://tic-project-46906.firebaseio.com",
    projectId: "tic-project-46906",
    storageBucket: "tic-project-46906.appspot.com",
    messagingSenderId: "131019956403"
  };
firebase.initializeApp(config);

app.use(bodyParser.urlencoded({extended : false}));
app.use(methodOverride('_method'));

const database = firebase.database();

app.use(express.static(path.join(__dirname, 'static')));

app.set('/views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + '/views/menu.html'));
});

// select w/o filters
app.get('/movies', (req, res) => {
    var value;
    const movies = []; 
    var keys = [];
    database.ref('movie-list').on('value', snapshot => {    
        snapshot.forEach(element => {
            movies.push(element.val());
            keys.push(element.key);
        });
    });
    res.render("movies.html", {
        data: movies,
        ids : keys
    });
});

// select one element + subchilds
app.get('/movies/:Id', (req, res, next) => {
    var reviews = [];
    database.ref('movie-list').orderByKey().equalTo(req.params.Id).once('value', snapshot => {
        var movie;
        snapshot.forEach(element => {
            movie = element.val();
        });

        res.render("movie-item.html", {
            data : reviews
        });
    });
});

// add elem
app.post('/movies/add', (req, res, next) => {
    console.log(req.body);
    const newMovieKey = database.ref('movie-list').push().key;
    database.ref('movie-list/' + newMovieKey).set(req.body);
    res.sendStatus(200);
});

// update
app.post('/movies/edit/:id', (req, res, next) => {
    console.log('update-called');

    database.ref('movie-list').orderByKey().equalTo(req.params.id).once('value', snapshot => {
        console.log(req.params.id);
        //database.ref('movie-list/' + req.params.id).update(req.body);
    });
});

// delete
app.delete('/movies/delete/:id', (req, res, next) => {
    console.log('delete called');
    console.log(req.params.id);
    database.ref('/movie-list/' + req.params.id).remove();
    res.sendStatus(200);
});

app.listen(8080, () => {
    console.log("Deschis pe portul 8080");
});

现在的问题是,每当我尝试在javascript中加载元素的处理程序时,只有第一个可以运行。由于我需要通过我从服务器获得的响应来处理我正在加载的每个元素的函数,所以我只能更新和删除添加的最后一个元素。我正在使用ajax向服务器发送请求。

因此,如果我按下编辑输入或删除锚点,它就不会让步。

以下是HTML页面内容:

<!DOCTYPE html>
<html>

<head>
    <title>Proiect TIC - Buruleanu</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="script.js"></script>
</head>
<body>
    <section class="main-body">
        <div class="wrapper">
            <div class="logo">
                <a href="#">
                    <img src="media/logo2.png" width="140px" height="120px">
                </a>
            </div>
            <div class="search-bar">
                Search by movie title...
            </div>
            <h2>MOVIES LIST</h2>
            <hr>
            <h4>The main sets for this week:</h4>
            <div class="content-section">
                <ul class="movies-list">
                    <% for(var i=0; i < data.length; i++) { %>
                        <li class='list-item'>
                            <div class='item-content'>
                                <div class='item-poster'>
                                    <img src='<%= data[i].PosterLocation %>' />
                                </div>
                                <div class='item-description'>
                                    <h4>
                                        <%= data[i].Title %>
                                    </h4>
                                    <%= data[i].Description %>
                                </div>
                                <div class='item-ratings'>
                                    <ul>
                                        <li>
                                            <p>IMDB rating:</p>
                                        </li>
                                        <li>
                                            <h4>
                                                <%= data[i].Rating %>/10
                                            </h4>
                                        </li>
                                        <li>
                                            <form action="/movies/edit/<%= ids[i] %>" method="post">
                                                <input id='edit-button' type="submit" value="Edit">
                                            </form>
                                        </li>
                                        <li>
                                            <a id='a-del' onclick'deleteFunction()' href='#<%= ids[i] %>'>Delete</a>
                                        </li>
                                    </ul>
                                </div>
                            </div>    
                        </li>
                        <% } %>
                         <div class="review-write-form">
                         <h3>Add or Update a movie</h3>
                        <form action="/movies/add" method="post">
                          Title: <input type="text" name="Title"><br>
                          Rating: <input type="number" name="Rating"><br>
                          PosterLocation: <input type="text" name="PosterLocation"><br>
                          Description: <input type="text" name="Description"><br>
                          <input type="submit" value="Submit">
                        </form>
                        </div>
                </ul>
                </div>
                <footer>
                    Proiect realizat de Buruleanu Ionut-Robert. Grupa 1091 E-business.
                </footer>
            </div>

    </section>
</body>

</html>

和javascript代码:

    $('document').ready(function() {
                 $('#a-del').click(function() {
                 console.log('we are here!');
                  var id = $('#a-del').attr('href');
                  console.log(id);
                  $.ajax({
                   url: '/movies/delete/' + id.replace('#',''),
                   type: 'DELETE',
                   success: function() {
                     console.log('succes');
                  },
                  error: function() {
                     console.log(error);
                  }
                  });
                });

                function deleteFunction() {
                console.log('we are here!');
                  var id = $('#a-del').attr('href');
                  console.log(id);
                    $.ajax({
                       url: '/movies/delete/' + id.replace('#',''),
                       type: 'DELETE',
                       success: function() {
                         console.log('succes');
                      },
                      error: function() {
                         console.log(error);
                      }
                    });
                };

                $('#edit-button').click(function() {
                    console.log('edit-clicked!');
                });
    });

我试图通过指示onclick函数强制html元素,并通过jquery操作它们。现在我真的不明白为什么在事件被触发时他们都没有发送任何输出。

提前致谢

1 个答案:

答案 0 :(得分:0)

您为编辑按钮和循环中所有按钮的删除按钮添加了相同的ID。

id上的jquery函数$(&#34; #myid&#34;)只绑定一次。

改用class:

<button href="yolo" id="a">A</button>
<button href="yala" id="a">A2</button>
$("#a").click(function(){ console.log($("#a").attr("href"))})


// click on the two button always display yolo

 <button href="yolo" class="a">A</button>
 <button href="yala" class="a">A2</button>

 $(".a").click(function(){ console.log($(this).attr("href"))})

 // click display the good values