简体   繁体   中英

Call Javascript function multiple times in a foreach loop

I have a search results list generated by a foreach loop. I am trying to add a button to each result, to open each search result in an iframe window, but only the first result works, not the others. I would like to be able to open one or more results in iframes in the same page. and be able to close them by clicking another button. Any ideas? Thanks

     foreach($this->result['web']->results->result as $item) {
 echo "<ul>";
 echo "<li><a href='".$item->url."'>".$item->title."</a></li>";
 echo "<li>".$item->abstract."</li>";
 echo "<script>$(function(){
 $('#button').click(function(){
 if(!$('#iframe').length) {
 $('#iframeHolder').html('<iframe id=\"iframe\" src=\"".$item->url."\"    width=100% height=\"600\"></iframe>');
}
});   
});</script>";       
echo"<li><a id=\"button\">Open</a></li>";
echo"<div id='iframeHolder'></div>";
echo "</ul>";
}
return true;
}

There are many problems with your approach, I'll try to enumerate them.

  1. You are using repeated IDs in your DOM ( button ). IDs should be unique .
    Use classes for repeatability. Check the HTML specification for more info.

  2. Your jQuery selector is using the IDs to bind the click function to the buttons.
    Every time you add a button, you bind all buttons to the function.

  3. You should have a generic click function that receives an event .
    Check jQuery docs for ways to fetch the clicked element from the event.


This will only help you a little. The last mile includes adding the item URL to your button or li .

I recommend using a data-x attribute, that you can fetch using jQuery's #data() function (eg target.data('x') ). In order to avoid setting the attribute value as the item URL, set it to an array index, for example.

Lastly, add your script tag to the end of the DOM, or in the head/separate file wrapped in a $(document).ready() call. It's best if it only runs after everything finished loading.

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