从链接获取javascript中的变量


Fetch variable in javascript from a link

我正试图通过javascript发送一个PHP变量,但遇到了问题。我使用的是我在网上找到的jQuery弹出窗口,当用户点击一个项目时,我需要在我想添加表单的弹出窗口中获取item_id变量。

我的PHP部分。

<a href="#?w=500&item_id='.$stock['id'].'" rel="popup1" class="poplight">

和Javascript。

$(document).ready(function(){
    //When you click on a link with class of poplight and the href starts with a # 
    $('a.poplight[href^=#]').click(function() {
        var popID = $(this).attr('rel'); //Get Popup Name
        var popURL = $(this).attr('href'); //Get Popup href to define size
        //Pull Query & Variables from href URL
        var query= popURL.split('?');
        var dim= query[1].split('&');
        var popWidth = dim[0].split('=')[1]; //Gets the first query string value
        var itemID = dim[0].split('=')[2]; //Gets the second query string value
        //Fade in the Popup and add close button
        $('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"><img src="/layout/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');
        //Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
        var popMargTop = ($('#' + popID).height() + 80) / 2;
        var popMargLeft = ($('#' + popID).width() + 80) / 2;
        document.getElementById('popup1').innerHtml = itemID;
        //Apply Margin to Popup
        $('#' + popID).css({ 
            'margin-top' : -popMargTop,
            'margin-left' : -popMargLeft
        });
        //Fade in Background
        $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
        $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer 
        return false;
    });

    //Close Popups and Fade Layer
    $('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
        $('#fade , .popup_block').fadeOut(function() {
            $('#fade, a.close').remove();  
    }); //fade them both out
        return false;
    });

});

我添加了我认为您工作的内容,但它没有var itemID = dim[0].split('=')[2]; //Gets the second query string valuedocument.getElementById('popup1').innerHtml = itemID;

使用复杂的函数检索URL查询参数:

function getParameterByName(name, locationObject)
{
  name = name.replace(/['[]/, "'''[").replace(/[']]/, "''']");
  var regexS = "[''?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(locationObject.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/'+/g, " "));
}

[从此处采用]

简单地这样称呼它:

getParameterByName('item_id', someLink);  

工作Fiddle:http://jsfiddle.net/ADpYT/

您在原始代码中有一个简单的疏忽。。当您获得dim变量时,您会得到一个数组,其中包含在&处拆分的2个项。在上面的代码中,你得到了["w=500", "item_id=some_value"]。所以为了得到itemID,你必须使用dim[1]。var itemID=dim[1].split('=')[1];