Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Как всем ссылкам в блоке присвоить onClick и в href поставить # (https://javascript.ru/forum/dom-window/79450-kak-vsem-ssylkam-v-bloke-prisvoit-onclick-i-v-href-postavit.html)

A.User 11.02.2020 13:50

Как всем ссылкам в блоке присвоить onClick и в href поставить #
 
Требуется в документе или блоке заменить все ссылки, вытащить из них содержимое href, поместить полученные ссылки в событие onClick(url_href), а href сделать "#" то есть чтобы клик происходил через функцию. Прошу подскажите реально ли такое сделать? Сам я новичек, но вот появилась задача организовать такое, хочу все ссылки открывать с помощью собития. Заранее благодарю.

Nexus 11.02.2020 13:56

var container = document.querySelector('block-selector');
if (!container) {
    return;
}

container.querySelectorAll('a[href]').forEach(function (node) {
    var href = node.getAttribute('href');

    node.addEventListener('click', function (e) {
        e.preventDefault();

        onClick(href);// onClick - you function name
    });

    node.href = '#';
});

A.User 11.02.2020 14:46

Благодарю! По коду смотрю, так вроде должно сработать, но запускаю и не работает :( Не пойму в чем дело... Прошу помочь.

Код:

<html>

<head>
    <script>
        function goURL(k) {
            alert(k);
        }

        var container = document.querySelector('.pages');
        if (!container) {
            return;
        }

        container.querySelectorAll('a[href]').forEach(function (node) {
            var href = node.getAttribute('href');

            node.addEventListener('click', function (e) {
                e.preventDefault();

                goURL(href);// onClick - you function name
            });

            node.href = '#';
        });
    </script>
</head>

<body>
    <div class="pages">
        <a href="http://site.com/page/2/">2</a>
        <a href="http://site.com/page/3/">3</a>
        <a href="http://site.com/page/4/">4</a>
        <a href="http://site.com/page/5/">5</a>
        <a href="http://site.com/page/6/">6</a>
        <a href="http://site.com/page/7/">7</a>
        <a href="http://site.com/page/8/">8</a>
        <a href="http://site.com/page/9/">9</a>
        <a href="http://site.com/page/10/">10</a>
        <a href="http://site.com/page/11/">11</a>
    </div>
</body>

</html>


рони 11.02.2020 14:53

A.User,
нет блока <div class="pages"> на момент работы скрипта. скрипт вниз страницы или читать про DOMContentLoaded

A.User 11.02.2020 14:56

Я поместил код перед /body и все равное не срабатывает...

A.User 11.02.2020 15:15

Убрал

if (!container) {
return;
}


заработало.

рони 11.02.2020 15:49

Цитата:

Сообщение от A.User
заработало.

:-? вы уверены?

рони 11.02.2020 15:52

A.User,
рабочий код
<html>

<head>

</head>

<body>
    <div class="pages">
        <a href="http://site.com/page/2/">2</a>
        <a href="http://site.com/page/3/">3</a>
        <a href="http://site.com/page/4/">4</a>
        <a href="http://site.com/page/5/">5</a>
        <a href="http://site.com/page/6/">6</a>
        <a href="http://site.com/page/7/">7</a>
        <a href="http://site.com/page/8/">8</a>
        <a href="http://site.com/page/9/">9</a>
        <a href="http://site.com/page/10/">10</a>
        <a href="http://site.com/page/11/">11</a>
    </div>
    <script>
        function goURL(k) {
            alert(k);
        }

        var container = document.querySelector('.pages');
        if (container) {
        container.querySelectorAll('a[href]').forEach(function (node) {
            var href = node.getAttribute('href');

            node.addEventListener('click', function (e) {
                e.preventDefault();

                goURL(href);// onClick - you function name
            });

            node.href = '#';
        });};
    </script>
</body>

</html>

или так
<html>

<head>
    <script>
  document.addEventListener( "DOMContentLoaded" , function() {
  function goURL(k) {
            alert(k);
        }

        var container = document.querySelector('.pages');
        if (!container) {
            return;
        };

        container.querySelectorAll('a[href]').forEach(function (node) {
            var href = node.getAttribute('href');

            node.addEventListener('click', function (e) {
                e.preventDefault();

                goURL(href);// onClick - you function name
            });

            node.href = '#';
        });
  });

    </script>
</head>

<body>
    <div class="pages">
        <a href="http://site.com/page/2/">2</a>
        <a href="http://site.com/page/3/">3</a>
        <a href="http://site.com/page/4/">4</a>
        <a href="http://site.com/page/5/">5</a>
        <a href="http://site.com/page/6/">6</a>
        <a href="http://site.com/page/7/">7</a>
        <a href="http://site.com/page/8/">8</a>
        <a href="http://site.com/page/9/">9</a>
        <a href="http://site.com/page/10/">10</a>
        <a href="http://site.com/page/11/">11</a>
    </div>
</body>

</html>

A.User 11.02.2020 16:38

Да, заработал тот вариант. А что, там есть явные ошибки?

рони 11.02.2020 16:56

Цитата:

Сообщение от A.User
Да, заработал тот вариант. А что, там есть явные ошибки?

ошибок нет, можно и просто убрать условие, если поставить скрипт вниз страницы, думал у вас заработало без переноса вниз.


Часовой пояс GMT +3, время: 09:20.