将查询字符串添加到URL

时间:2011-12-18 22:37:51

标签: jquery string url

var EventAddress=$(".EventAddress").text();
$(".EventDirectionLink a").attr("href", url + EventAddress);  

这是我用来从表格单元格中获取地址值的jquery,并将其作为查询字符串传递给地图网址,但它不起作用?我做错了什么?

<div class="driving-directions-link">
<a href="http://maps.google.com/maps?q=">Get Direction</a>
</div>

<table cellpadding="10" class ="EventDetail">
    <tr>
        <td class="TableFields">Who Should Enroll?:</td>
        <td>Everyone 18 and older who would like to attend</td>
    </tr>
    <tr>
        <td class="TableFields">Location:</td>
        <td class="EventAddress">1300 Albany Street,Beech Grove ,IN</td>
    </tr>
</table>

5 个答案:

答案 0 :(得分:4)

试试这个:

$('td.EventAddress').click(
    function(){
        $(".driving-directions-link a").attr("href", $(this).attr('href') + encodeURIComponent($(this).text)); 
    });

JS Fiddle demo

简化上述内容,避免两次使用.attr()方法(第二次不必要):

$('td.EventAddress').click(function(){
    $(".driving-directions-link a").attr("href", function(i, h) {
        return h + encodeURIComponent($(this).text());
    });

JS Fiddle demo

参考文献:

答案 1 :(得分:0)

<div class="EventDirectionsLink">
<a href="http://maps.google.com/maps?q=">Get Direction</a>
</div>

<table cellpadding="10" class ="EventDetail">
    <tr>
        <td class="TableFields">Who Should Enroll?:</td>
        <td>Everyone 18 and older who would like to attend</td>
    </tr>
    <tr>
        <td class="TableFields">Location:</td>
        <td class="EventAddress">1300 Albany Street,Beech Grove ,IN</td>
    </tr>
</table>
var EventAddress=$(".EventAddress").text();
$(".EventDirectionsLink > a").attr("href", $('.EventDirectionsLink > a).attr('href') + EventAddress);  

答案 2 :(得分:0)

$(".driving-directions-link > a").attr("href", "http://maps.google.com/maps?q=" + EventAddress);

答案 3 :(得分:0)

var EventAddress = encodeURIComponent($(".EventAddress").text());
$(".EventDirectionLink a").attr("href", url + "q=" + EventAddress);  

请记住在使用之前解码查询字符串。

答案 4 :(得分:0)

我尝试使用以下方法添加查询字符串时遇到类似问题:

$(this).attr("href", url + queryString);

添加了网址,但没有添加queryString。

我使用了javascript concat方法,这似乎有效:

var queryString = '?myVar=test';
//Replace the url with an additional query string
$(this).attr('href', $(this).attr('href').concat(queryString));