简体   繁体   English

如何将 Jquery 值绑定到 HTML 元素

[英]How to Bind Jquery Value to an HTML Element

How can i bind the url result from the jquery to the href ?如何将 jquery 的 url 结果绑定到 href ? as you can see on the html below.正如您在下面的 html 中看到的那样。 Thank you.谢谢你。

JQUERY CODE查询代码

<script>
$(document).ready(function(){
   $("#btnSearch").click(function(){
       var yearArray = []; 
      $("input:checkbox[name=Year]:checked").each(function(){
         yearArray.push($(this).val());
       });
       var makeArray = []; 
      $("input:checkbox[name=Make]:checked").each(function(){
         makeArray.push($(this).val());
       });
      var url="http://example.com/results?Year="+yearArray.join()+"&Model="+makeArray.join();
        alert(url);
   });
});

</script>

HTML HTML

<a href="/searchnew/{{ url }}"><button id="btnSearch" class="btn btn-cta margin-bottom-1x search-button cssBase"
                                        type="button""
                                        style="width: 262.5px;">Search</button></a>

You can simpy add href attribute after creating link.创建链接后,您可以简单地添加 href 属性。 What i mean by this is if your href tag is look like this我的意思是如果你的 href 标签看起来像这样

<a href="#" id="myurl">
$("#myurl").prop("href",url);

This will simply render your html like this这只会像这样呈现您的 html

<a href="http://example.com/results?Year="......(your dynamic values here)">

You don't have to add tag on to button click.您不必为按钮单击添加标签。 Instead, on click of button, within the function after you have prepared url, call相反,单击按钮,在准备好 url 后的函数中,调用

location.href = "searchnew/" + url; location.href = "searchnew/" + url;

In case you have the base url for the app, you can prepend as well to have the complete url with you.如果您有应用程序的基本网址,您也可以预先准备好完整的网址。

Use id attribute for your a tag like this-为您的标签使用 id 属性,如下所示 -

<a href="....." id="myLink" > ... </a>

And at the end of your jQuery code add the following:在 jQuery 代码的末尾添加以下内容:

var a = $('#myLink');
var href = a.attr('href');
a.attr('href', href + url);

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

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