1

这是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);   
    }
4

2 回答 2

1

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

$('a[href="'+existingUrl+'"]').attr('href', resultUrl);
于 2012-08-18T13:27:20.393 回答
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);
于 2012-08-20T07:52:45.370 回答