简体   繁体   English

javascript 只工作一次,首先<a></a>

[英]javascript only works once, on first <a>

I am making "food blog" project where you can add and delete a category to the recipe sucha as pasta, veggie and vlees (=meat).我正在制作“美食博客”项目,您可以在其中添加和删除食谱的类别,例如意大利面、蔬菜和 vlees(=肉)。 it works fine with php but when I try to do it with javascript the adding of a category works fine but the deletion of a category only works on the first element.它适用于 php 但当我尝试使用 javascript 时,添加类别可以正常工作,但删除类别仅适用于第一个元素。 on all other elements, even elements(categories) I added with javascript it just does it with php and not with javascript for some reason.在所有其他元素上,甚至元素(类别)我添加了 javascript 它只是使用 php 而不是 javascript 出于某种原因。

So I need to find in the javascript what is causing it to only work on the first one.所以我需要在 javascript 中找到导致它仅适用于第一个的原因。

JAVASCRIPT. JAVASCRIPT。 the function that deletes the category is handleClickDelete and the event listener is in the init();删除类别的function是handleClickDelete,事件监听器在init()中;

const handleClickDelete = async e => {
      
            const confirmed = window.confirm('Bent u zeker dat u deze categorie wilt verwijderen?');

            e.preventDefault();
          

            if (!confirmed) {
              return
            }
          
            let getcategoryId = new URLSearchParams(`${document.querySelector('.detail__link').getAttribute('href')}`);
        console.log(getcategoryId);
        const categoryId = getcategoryId.get('category_id');
        console.log(categoryId);
      
        const url = `${document.querySelector('.detail__link').getAttribute('href')}`;
        console.log(url);
        
        const searchParams = new URLSearchParams(window.location.search);
        const recipeId = searchParams.get('id');
        console.log(recipeId);
        
       
        // versturen naar de juiste route op de server en aangeven dat we een JSON response verwachten
        // de parameter body bevat de data 
        const response = await fetch(url, {
            method: "POST",
            headers: new Headers({
                'Content-Type': 'application/json'
            }),
            body: JSON.stringify({
                id: categoryId,
                recipe_id: recipeId,
                action: "deletePost"
            })
            
            
            
        });
        
        // PHP Response. Contains error or updated reaction value
        
        const returned = await response.json();

        
        console.log(returned);
        
        

        showCategories(returned);
          
        
      

        
        
        


        
        
    };
    


    //insert
   

    const postCategory = async () => {

        let getValue = document.querySelector('.categories_select');
        let categoryId = getValue.value;
        if(categoryId === "-1"){
            return

        }
        
        const url = `${document.querySelector('.form__category').getAttribute('action')}`;
        console.log(url);
        
        const searchParams = new URLSearchParams(window.location.search);
        const recipeId = searchParams.get('id');
        
        //console.log(url);
        //console.log(test);
        //console.log(test2);
        // versturen naar de juiste route op de server en aangeven dat we een JSON response verwachten
        // de parameter body bevat de data (in dit geval quoten auteur en id van de aflevering)
        const response = await fetch(url, {
            method: "POST",
            headers: new Headers({
                'Content-Type': 'application/json'
            }),
            body: JSON.stringify({
                category_id: categoryId,
                recipe_id: recipeId,
                action: "add-category"
            })
            
            
        });
        // PHP Response. Contains error or updated reaction value
        
        const returned = await response.json();

        
        console.log(returned);

        
        showCategories(returned);

     
    };

    const showCategories = categories => {
        const $categories = document.querySelector('.detail__foreach');
        // elementen aanmaken via JavaScript ipv via PHP
        $categories.innerHTML = categories.map(category => {
          console.log(category);
          return `
          

          <div class="detail__category--box">
                <p class="detail__category">${category.name} </p>
                <a class="delete-link detail__link" href="index.php?page=detail&id=${category.id}&action=deletePost&category_id=${category.category_id}">delete</a></br>
          </div>
         
          `;
        }).join(``);
        
        
      };
    
    const hideButton = () => {
        const $filterbutton = document.getElementById('submit__button');
        $filterbutton.classList.add('hidden');
      }

    const init = () => {
        const $categoryButtons = document.querySelectorAll('.categories_select');
        $categoryButtons.forEach(element => {
            element.addEventListener('change', postCategory);
        });

        const links = document.querySelectorAll('.delete-link');
        links.forEach($link =>  {
            $link.addEventListener('click', handleClickDelete);
            
            

        });
        
        
        hideButton();

        
    };

    init();

ImagesDAO the if ($data['action'] == 'deletePost') is where the deleting gets performed ImagesDAO if ($data['action'] == 'deletePost')是执行删除的地方

public function jsonAddCategory() 
    {
        //? Add reactions via JS
        // POST from JavaScript
        $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
        if ($contentType === "application/json") {
            $content = trim(file_get_contents("php://input"));
            $data = json_decode($content, true);
            

            //? JS REACTION
            // Check if it is add reaction
            if ($data['action'] == 'add-category') {
                $updatedCategory = $this->insertImage($data);

                $category = $this->selectCategoriesByPost($_GET['id']);
                echo json_encode($category);
                exit();
            }

            if ($data['action'] == 'deletePost') {
              $id = $data['id'];
              $recipe_id = $data['recipe_id'];
              $deletedCategory = $this->delete($id, $recipe_id);

            
              $selectedCategory = $this->selectCategoriesByPost($_GET['id']);
              
              echo json_encode($selectedCategory);
              exit();
          }
        };
    }

PagesTDTController PagesTDTController

  public function detail() {
    if (!empty($_GET['id'])) {
      $image = $this->imagesDAO->selectById($_GET['id']);
      $this->set('image', $image);
      
      $ingredients = $this->imagesDAO->selectIngredientenById($_GET['id']);
      $this->set('ingredients', $ingredients);

      $categories = $this->imagesDAO->selectAllCategories();
      $this->set('categories', $categories);
      
      $recipe_category = $this->imagesDAO->selectCategoriesById($_GET['id']);
      $this->set('recipe_category', $recipe_category);

      $category_recipes = $this->imagesDAO->selectCategoriesByPost($_GET['id']);
      $this->set('category_recipes', $category_recipes);
      $this->imagesDAO->jsonAddCategory();

   

      

    }
    if (empty($image)) {
      $_SESSION['error'] = 'The post could not be found';
      header('Location: index.php');
      exit();
      
    }


    

    if (!empty($_POST['action'])) {
      if ($_POST['action'] == 'add-category') {
        if($_POST['categories'] != 'Select category'){
          $data = array(
            'recipe_id' => $image['id'],
            'category_id' => $_POST['categories']
          );
          $insertedImage = $this->imagesDAO->insertImage($data, $_GET['id']);
          if (empty($insertedImage)) {
            $errors = $this->imagesDAO->validateImage($data);
            $this->set('errors', $errors);
          } else {
            $_SESSION['info'] = 'Category succesfully added!';
            header('Location: index.php?page=detail&id=' . $image['id']);
            exit();
            
          }

        }
        
        
      }
    }

    if(!empty($_GET['action'])){
      if($_GET['action'] == 'deletePost' && !empty($_GET['category_id'])){
          $this->imagesDAO->delete($_GET['category_id'], $image['id']);
      }
          $_SESSION['info'] = 'Succesfully deleted category!';
          header('Location: index.php?page=detail&id=' . $image['id']);
          exit();
    }



  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM