开发者

Using #urls in jquery

I've managed to confuse myself here. Basically I am using jQuery to turn a div into a link with;

$('.product').click(function() {
window.open('product.php','jav');
}); 

This works fine but I am using a .php/MySQL database and I want to be able to pass the product ID into the url so it goes to /product.php#$id. Normally I'd just use <a> tags in my php code but using the Javascript method I can't plug in the PHP var开发者_如何转开发iable to the URL.

Probably not making a lot of sense but it's been a long day, happy to answer any questions if it's a little difficult to make out what I'm asking for here.


Emit the product ID as part of the div's markup. Here I've shown two options: a data- attribute and the contents of the div. I'd prefer the data- attribute since your content is probably already defined. You can see all that is below on jsfiddle.

<div class="product" data-id="42">42</div>

Now access it when building your URL:

$('.product').click(function() {
    //window.open('product.php','jav');

    var id = $(this).data('id'); // Alternatively use .attr('data-id')
    alert('product.php#' + id); 

    var text = $(this).text();
    alert('product.php#' + text);
});


If you put the id in a custom attribute you can pull it on the click event:

For example:

<div class=".product" urlid="someproductid"></div>

then later in your click event handler you can use jQuery's attr method to get the value.


Well, you need to have the id somewhere in your markup. If .product are <a>, you can assign to each one the complete url, like:

<a href="product.php?id=333">

So, in your jquery code:

$('.product').click(function() {
     window.open($(this).attr('href'),'jav');
     return false;
}); 

(Not tested)

ADDED: Missing return false;

This will also works if user has js disabled, as it will navigate to the right page instead of opening it as popup.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜