<div class="b-filter__field" id="sort_selector"> {%if $get == "t"%}<span>{%else%}<a href="" data-value="t">{%/if%}По популярности{%if $get == "t"%}</span>{%else%}</a>{%/if%} {%if $get == "v"%}<span>{%else%}<a href="" data-value="v">{%/if%}По времени публикации{%if $get == "v"%}</span>{%else%}</a>{%/if%} {%if $get == "r"%}<span>{%else%}<a href="" data-value="r">{%/if%}По рейтингу{%if $get == "r"%}</span>{%else%}</a>{%/if%} </div> <script> $(document).ready(function(){ $("#sort_select").bind("click", function(e){ e.preventDefault(); var v = $("a").data('value'); console.log(v); // Он даже не доходит до сюда, а по ссылке все равно переходит. var loc = location.href + "&sort=" + v; document.location.href = loc; }); }); 

I want a click to add a get parameter to the link, but I cannot get the value of the user attribute. Tell me, what is the error?

  • You have id="sort_selector , and you use $("#sort_select") - Andrew B

1 answer 1

 $(document).ready(function(){ //селектор должен содержать в точности такой же id, какой используется в коде, кроме того, при селекции только по id div'a, событие будет срабатывать по клике на див, а не на ссылку, поэтому уже на этом шаге происходила ошибка // выбираются все теги a внутри элемента с id = sort_selector $("#sort_selector > a").bind("click", function(e){ //убираем дефолтные события e.preventDefault(); //получаем в v значение href cсылки, в случае, если оно заполнено для тега a, то нужно включить его в общую сумму z, таким образом, чтобы получилось //z=window.location.toString()+v+"&sort="+$(this).attr('data-value'); var v = $(this).attr('href'),separator,z; //проверяем, нет ли в адресной строке ?, чтобы не использовать его повторно (window.location.search.substring(-1,1))?separator="&":separator="?"; //собираем ссылку из адресной строчки+сепаратора (полученного на предыдущем шаге)+get параметра sort+атрибута data-value элемента a, по которому был произведен клик z=window.location.toString()+separator+"sort="+$(this).attr('data-value'); //выводим получившийся линк в консоль console.log(z); //раскомментировать для перехода - осушествляем переход //window.location =z; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="b-filter__field" id="sort_selector"> <!-- теги должны иметь правильную вложенность, либо span внутри a, либо наоборот, чаще всего первый вариант предпочтительнее, хотя оба элемента инлайновые--> <a href="#1" data-value="t"><span>По популярности</span></a> <a href="#2" data-value="v"><span>По времени публикации</span></a> <a href="#3" data-value="r"><span>По рейтингу</span></a> </div> 

  • What in this code is different from the code in the question? - Grundy
  • @Grundy, fixed selector, fixed nesting of tags, changed calls to non-existent attributes, set the check for "?" In the address bar, in order to avoid duplicate or missing characters, a workable code is given - Rager
  • one
    @TimurMusharapov first is getting the href attribute of the link, the second is checking whether there is a question mark in the address bar so as not to insert it the second time window.location has several properties in it, one of them is responsible for the line after the question mark, including it. The substring method makes a string from a string into the first character. - Rager
  • one
    @TimurMusharapov use the indexOf () method - Rager
  • one
    @TimurMusharapov, in this case, no difference: first, the variable v is declared and immediately initialized with its value, and then the separator and z variables are declared separated by a comma,