need to extract certain values from attribute and place them in variables
In the following markup on a page I want to extract out the following and put them in seperate variables.
1- In the onclick attribute get the value after the "ProductID" and put it in its own variable. "ProductID" So in this case it would be 318
2- In the onclick attribute get the value after the "Orig_price" and put it in a variable, "Orig_Price" So in this case it would be 22.95
3- In the onclick attribute get the value after the "width" and put it in a variable, "width" So in this case it would be 330
4- In the onclick attribute get the value after the "height" and put it in a variable, "height" So in this case it would be 300
<a href="javascript:void(0);" onclick="window.open('/BulkDiscounts.asp?ProductID=318&ProductCode=' + escape('LB30X40ES') + '&Orig_Price=22.95', 'Discounts', 'scrollbars,status,resizable,width=330,height=300');">&开发者_运维百科lt;img src="/v/vspfiles/templates/100/images/buttons/btn_quantitydiscounts.gif" border="0" align="absmiddle"></a>
UPDATED DEMO:
DEMO: http://jsbin.com/axuce3/3 SOURCE: http://jsbin.com/axuce3/3/edit
var pieces = $('a').attr('onclick').toString().split('?')[1].split('=');
var parts = [];
for (var i = 0; i < pieces.length; i++) {
var value = parseFloat(pieces[i]);
if (!isNaN(value)) parts.push(value);
}
alert( 'ProductID=' + parts[0] + 'Orig_price=' + parts[1] + 'width=' + parts[2] + 'height=' + parts[3]);
Please forget my previous answer, it was wrong (to test it, I assigned an id
to the wrong element). You can get the value of the onclick
attribute using getAttribute
. For testing purposes, I changed your example to
<a href="javascript:void(0);" id="test" onclick="window.open('/BulkDiscounts.asp?ProductID=318&ProductCode=' + escape('LB30X40ES') + '&Orig_Price=22.95', 'Discounts', 'scrollbars,status,resizable,width=330,height=300');"><img src="/v/vspfiles/templates/100/images/buttons/btn_quantitydiscounts.gif" border="0" align="absmiddle"></a>
Now document.getElementById("test").getAttribute("onclick")
returns
window.open('/BulkDiscounts.asp?ProductID=318&ProductCode=' + escape('LB30X40ES') + '&Orig_Price=22.95', 'Discounts', 'scrollbars,status,resizable,width=330,height=300');
Now you can get the values using
var theString = document.getElementById("test").getAttribute("onclick");
var ProductID = theString.match(/ProductID=(\d*)/i)[1];
var Orig_Price = theString.match(/Orig_price=([\d\.]*)/i)[1];
var width = theString.match(/width=(\d*)/i)[1];
var height = theString.match(/height=(\d*)/i)[1];
(code is stolen from Tambourine's answer, so please give him the credits ;).
Try this code:
var string = $('a').attr('onclick') + ""; // to be sure var string is string
ProductID = string.match(/ProductID=(\d*)/i)[1];
Orig_Price = string.match(/Orig_price=([\d\.]*)/i)[1];
width = string.match(/width=(\d*)/i)[1];
height = string.match(/height=(\d*)/i)[1];
精彩评论