首页 > 解决方案 > 错误推送 javascript 无法正常工作?

问题描述

使用push方法将数据输入数组时发现了一个bug,bug是数据进入索引0(索引只卡在2),如下图所示:

这里是控制台的输出

在此处输入图像描述

这是我的脚本:

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

    <script>
        let btn = $("#btn");
        let target = $("#target");
        let genre = $("#genre");

        btn.click(function() {
            target.toggleClass('hidden');
            target.hasClass('hidden') ? btn.text('Opsi Lain') : btn.text('Sembunyikan');
        });

        genre.on('keyup', function() {
            let query = $(this).val();

            if (query != '' || query != null) {
                let autocomplete = $("#genre-list");

                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    url: "http://localhost/autocomplete/fetch",
                    method: "post",
                });

                $.ajax({
                    data: {
                        query: query
                    },
                    success: function(data) {
                        // console.log(data);
                        autocomplete.fadeIn();
                        autocomplete.html(data);
                    }
                });

            }

        });

        $("form").on('click', 'a', function() {
            let arr = [$("div strong").text()];
            arr.push($(this).text());
            console.log(arr);

            let value = `<strong name="genres" value="${$(this).text()}" class="inline-flex my-1.5 mr-2 bg-cool-gray-300 normal-case text-center rounded-sm pl-1.5 pr-1 h-4 no-underline text-xs py-0 tracking-normal font-normal cursor-pointer box-border items-center">${$(this).text()}<svg data-icon="cross" style="fill: currentcolor;" viewBox="0 0 16 16" class="ml-1 w-3 h-3 box-border"><path d="M9.41 8l3.29-3.29c.19-.18.3-.43.3-.71a1.003 1.003 0 00-1.71-.71L8 6.59l-3.29-3.3a1.003 1.003 0 00-1.42 1.42L6.59 8 3.3 11.29c-.19.18-.3.43-.3.71a1.003 1.003 0 001.71.71L8 9.41l3.29 3.29c.18.19.43.3.71.3a1.003 1.003 0 00.71-1.71L9.41 8z" fill-rule="evenodd"></path></svg></strong>`;
            genre.before(value);
            genre.val('');
            $("#genre-list").fadeOut();
        });

        $("form").on('click', 'svg', function() {
            $(this).parent().remove();
        });
    </script>

和我的表格:

<form action="{{ route('private.store') }}" method="POST">
            @csrf
            <div class="shadow overflow-hidden sm:rounded-md">
                <div class="px-4 py-5 bg-white sm:p-6">
                    <div class="ml-12 md:ml-52">
                        <div class="mb-5">
                            <label for="title" class="block text-sm font-medium text-gray-700">Title</label>
                            <input type="text" value="{{ old('title') }}" name="title" id="title" class="mt-1 form-input w-full md:w-3/6 text-gray-700" placeholder="title anime">
                            @error('title') <p class="mt-1"><span class="px-1 font-semibold rounded-full bg-red-400 text-white"> {{ $message }} </span></p>
                            @enderror
                            @error('genres') <p class="mt-1"><span class="px-1 font-semibold rounded-full bg-red-400 text-white"> {{ $message }} </span></p>
                            @enderror
                        </div>

                        <div class="mb-5">
                            <label for="genre" class="block text-sm font-medium text-gray-700">Genre</label>
                            <div class="w-full md:w-3/6 inline-flex flex-wrap items-center shadow-sm z-10  appearance-none bg-white border rounded-md text-base px-2 py-2">
                                <input type="text" value="{{ old('genre') }}" name="genre" id="genre" placeholder="What Genre ?" class=" text-gray-700 text-xs tracking-normal leading-4 flex-grow h-7 box-border" autocomplete="off">
                            </div>
                            <div id="genre-list"></div>
                        </div>

                        <div class="mb-5">
                            <label for="link" class="block text-sm font-medium text-gray-700">Tempat Nonton</label>
                            <input type="text" name="link" value="{{ old('link') }}" id="link" placeholder="https://nanime.us" class="mt-1 form-input w-full md:w-3/6 text-gray-700">
                            @error('link')
                            <p class="mt-1"><span class="px-1 font-semibold rounded-full bg-red-400 text-white"> {{ $message }} </span></p>
                            @enderror
                        </div>

                        <div class="mb-5">
                            <div class="flex items-start">
                                <div class="flex items-center h-5">
                                    <input id="status" name="status" value=1 type="checkbox" class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded" @if (old('status')) checked @endif>
                                </div>
                                <div class="ml-3 text-sm">
                                    <label for="status" class="font-medium text-gray-700">Perlihatkan ke Public?</label>
                                </div>
                            </div>
                        </div>


                        <div id="target" class="hidden">
                            <div class="mb-5">
                                <label for="motivasi" class="block text-sm font-medium text-gray-700">Motivasi</label>
                                <textarea rows="4" name="motivasi" id="motivasi" class="w-full md:w-3/6 resize-none mt-1 form-input text-gray-700">{{ old('motivasi') }}</textarea>
                                @error('motivasi')
                                <p class="mt-1"><span class="px-1 font-semibold rounded-full bg-red-400 text-white"> {{ $message }} </span></p>
                                @enderror
                            </div>
                        </div>

                        <div class="bg-white">
                            <button type="button" id="btn" class="mb-5 inline-flex justify-center py-1 px-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                Opsi Lain
                            </button>
                            <button type="submit" class="mb-5 ml-48 sm:ml-96 md:ml-96 inline-flex justify-center py-1 px-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                Create
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>

当用户点击href链接时会生成强标签,并且href链接是从控制器生成的,以及控制器的内容

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AutocompleteController extends Controller
{
    function fetchGenre(Request $request)
    {
        $query = $request->get('query');

        $kondisi = DB::table('ajax')
            ->where('for', '=', 'genre')
            ->where('value', 'LIKE', "{$query}%")->exists();

        if ($query && $kondisi) {
            $data = DB::table('ajax')
                ->where('for', '=', 'genre')
                ->where('value', 'LIKE', "{$query}%")
                ->get();
            $output =  '<div class="origin-top-right right-0 mt-2 w-56 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 divide-y divide-gray-100">';
            foreach ($data as $row) {
                $output .= '<div class="py-1"> <a href="#" class="pilih block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hover:text-gray-900" role="menuitem">'.$row->value.'</a> </div>';
                $output .= '</div>';
                return $output;
            }
        } 
        elseif (!$kondisi) {
            $err =  '<div class="origin-top-right right-0 mt-2 w-56 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 divide-y divide-gray-100">';
            $err .= '<div class="py-1"> <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hover:text-gray-900" role="menuitem">Genre tidak di temukan!</a> </div>';
            $err .= '</div>';
            return $err;
        }
        else {
            $kosong = '';
            return $kosong;
        }
    }
}

标签: javascriptjqueryarrayslaravel

解决方案


#通过以下方式解决

我将变量的位置从本地更改为全局

我将变量的位置从本地更改为全局

谢谢你的指导:)


推荐阅读