使用href值查找锚标记并使用新的href值更改href值

时间:2012-08-18 13:23:35

标签: javascript jquery html javascript-events

这是html代码

<td>
<a class="buttontext" href="/kkdmpcu/control/MilkDeliveryScheduleReport.txt?shipmentId=10306&amp;reportTypeFlag=milkDeliverySchedule" target="_blank" onclick="javascript:setSelectedRoute(this, 10306);" title="Milk Delivery Schedule">Delivery Schedule</a>
</td>
<td>
<a class="buttontext" href="/kkdmpcu/control/KVGenerateTruckSheet.txt?shipmentId=10306&amp;reportTypeFlag=abstract" target="_blank" onclick="javascript:setSelectedRoute(this, 10306);" title="Abstract Report">Route Abstract Report</a>
</td>

我有href值。使用href值我应该找到锚标记并使用jquery将href值更改为新值。这是我目前没有的代码。

$('a[href$=(existingUrl)]'); // existingUrl is the href value I have
    .attr('href', resultUrl);  // resultUrl is the url that I need to replace with existingUrl.

//The whole code I have Right now

function setSelectedRoute(existingUrl, shipmentId) {

        var updatedUrl = existingUrl.toString();
        var facilityIndex = updatedUrl.indexOf("facilityId");

        if(facilityIndex > 0){
            updatedUrl = updatedUrl.substring(0, facilityIndex -1);
        }
        var form = $("input[value=" + shipmentId + "]").parent();
        var routeId = form.find("option:selected").text();
        var resultUrl = updatedUrl + "&facilityId=" + routeId;
        alert(resultUrl);

        $('a[href='+existingUrl+']').attr('href', resultUrl);   
    }

2 个答案:

答案 0 :(得分:1)

你不应该在选择器和attr方法之间使用分号,如果existingUrl是你应该连接的变量,请尝试这样:

$('a[href="'+existingUrl+'"]').attr('href', resultUrl);

答案 1 :(得分:0)

this不是href属性,它是a标记本身,这是第一个错误,因此existingUrl将获取对象。

更改代码

function setSelectedRoute(existingUrl, shipmentId) {

        var updatedUrl = $(existingUrl).attr('href'); // first instance
        // or var updatedUrl = existingUrl.getAttribute('href');

        var facilityIndex = updatedUrl.indexOf("facilityId");

        if(facilityIndex > 0){
            updatedUrl = updatedUrl.substring(0, facilityIndex -1);
        }
        var form = $("input[value=" + shipmentId + "]").parent();
        var routeId = form.find("option:selected").text();
        var resultUrl = updatedUrl + "&facilityId=" + routeId;
        alert(resultUrl);

        $('a[href="'+$(existingUrl).attr('href')+'"]').attr('href', resultUrl);  //second instance
    }

对于第二个实例,您可以直接使用existingUrl

$(existingUrl).attr('href', resultUrl);