这是html代码
<td>
<a class="buttontext" href="/kkdmpcu/control/MilkDeliveryScheduleReport.txt?shipmentId=10306&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&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);
}
答案 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);