简体   繁体   中英

click-able div open in new window

Easy enough to make a div with a background image clickable:

$(".socialMedia").click(function(){
             window.location=$(this).find("a").attr("href");
             return false;
        });

How can you make that open in a new window, its not using the anchor's target element, when I switch window.location to window.open i get an error. Is it possible? thx

$('.socialMedia').click(function(e){
  e.preventDefault();
  window.open($(this).find('a:first').attr('href'), '');
});

In this bit of JavaScript we are selecting all elements that have the socialMedia class. We then bind a callback function to each of these elements. This function defines one parameter, e , that represents the jQuery Event object.

Now, when a user clicks one of the socialMeda elements our callback function executes. First, the function uses the jQuery event.preventDefault() method to stop the browser from performing any default actions (eg go to a URL defined in a clicked link element). Then we use the window.open() method to open our desired URL. We get this URL by finding the first link element within the socialMedia element that was clicked (just in case there are multiple links).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM