Якорные теги в тегах li не активируются? - PullRequest
1 голос
/ 17 января 2020

Итак, у меня есть панель поиска с инвентарем. Панель поиска состоит из неупорядоченного списка с элементами списка, внутри которых есть якоря. Каждый якорь имеет ссылку на страницу, указанную c для этого элемента в списке. Проблема, с которой я сталкиваюсь (я полагаю) состоит в том, что событие щелчка мышью на якоре заставляет его исчезнуть, поэтому событие щелчка мышью, которое должно вызвать перенаправление на href, никогда не запускается, потому что элементы списка уже к тому времени исчез. Я нашел это сообщение: Якорный тег не работает внутри элемента списка

Похоже, что он ссылается на аналогичную проблему, и я подумал, что могу просто импортировать jquery в раздел заголовка моего html файл с

    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>   
    I then thought I could just put 
    <script>
    $("a").mousedown(function(ev) {
    ev.preventDefault();
    }
    </script>
inside the head tag but it doesn't work, does anyone have any insights?

The search bar list looks like:
    <input style="border-radius: 7px 0px 0px 7px; border-right: 0px; resize: 
    none" id="myInput" onkeyup="myFunction()" name="searchedItem" rows="1" 
    class="form-control" form="searchForm" placeholder="What can we help you 
    find?">
                      <ul id="myUL">
                        <li><a href="#">Air Tile Chipper</a></li>
                        <li><a href="#">Compressor (Electric)</a></li>
                      </ul>

    and the javascript it runs on is

    <script>
    var UL = document.getElementById("myUL");
    // hilde the list by default
    UL.style.display = "none";

    var searchBox = document.getElementById("myInput");

    // show the list when the input receive focus
    searchBox.addEventListener("focus",  function(){
        // UL.style.display = "block";
    });

    // hide the list when the input receive focus
    searchBox.addEventListener("blur", function(){
        UL.style.display = "none";
    });


    function myFunction() {
        var input, filter, ul, li, a, i;
        input = document.getElementById("myInput");
        ul = document.getElementById("myUL");
        filter = input.value.toUpperCase();
        // if the input is empty hide the list
        if(filter.trim().length < 1) {
            ul.style.display = "none";
            return false;
        } else {
            ul.style.display = "block";
        }

        li = ul.getElementsByTagName("li");
        for (i = 0; i < li.length; i++) {
            a = li[i].getElementsByTagName("a")[0];

            // This is when you want to find words that contain the search 
    string
         if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
         } else {
            li[i].style.display = "none";
        }

        // This is when you want to find words that start the search string
        /*if (a.innerHTML.toUpperCase().startsWith(filter)) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }*/
        }
    }
    </script>

1 Ответ

0 голосов
/ 17 января 2020

Использование event.preventDefault не останавливает выполнение других событий. Попробуйте использовать либо return false, либо event.stopImmediatePropogation.

...