最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - onclick not working on <li> - Stack Overflow

programmeradmin5浏览0评论

I am trying to get it so that when a specific <li> is clicked, an image is displayed on the same page.

Below is the code that determines which images to use. It seems to work fine, but I am including it anyway in case it contributes to the problem.

 <?php
  $j = 0;
  if (file_exists("u/".$_SERVER["REMOTE_ADDR"])) {
    $lines = array_reverse(array_unique(file("u/".$_SERVER["REMOTE_ADDR"])));
    $c = count($lines);
    $c = ($c > 20)?20:$c;
    for ($i = 0; $i < $c; $i++) {
      $lines[$i] = trim($lines[$i]);
      if (file_exists($lines[$i])) {
    echo "<li id=\"item$j\" title=\"".$lines[$i]."\" onclick=\"\"><a id=\"link$j\" href=\"#\">".$lines[$i]."</a></li>";
    $j++;
      }      
    }
   }
 ?>  

The following javascript applies the onclick to each element:

 <script type="text/javascript">
    for (i = 0; i < <?php echo $j; ?>; i++) {
      iLINK = $("item"+i).get("title");
      iHTML = "<img src=\""+iLINK+"\" />";
      $("item"+i).setAttribute("onclick","$('photogal').innerHTML = " +iHTML);
       }
 </script>

When loading the page, the <li> elements are aesthetically fine. When inspecting the element I see the following (which appears to be correct):

When changing the last line of javascript to:

$("item"+i).setAttribute("onclick","$('photogal').innerHTML = iHTML");

the onclick works as expected, although all links cause the final image to show (because after the loop, iHTML ends up being whatever the last instance of iHTML was).

What is the problem in this code?

I am trying to get it so that when a specific <li> is clicked, an image is displayed on the same page.

Below is the code that determines which images to use. It seems to work fine, but I am including it anyway in case it contributes to the problem.

 <?php
  $j = 0;
  if (file_exists("u/".$_SERVER["REMOTE_ADDR"])) {
    $lines = array_reverse(array_unique(file("u/".$_SERVER["REMOTE_ADDR"])));
    $c = count($lines);
    $c = ($c > 20)?20:$c;
    for ($i = 0; $i < $c; $i++) {
      $lines[$i] = trim($lines[$i]);
      if (file_exists($lines[$i])) {
    echo "<li id=\"item$j\" title=\"".$lines[$i]."\" onclick=\"\"><a id=\"link$j\" href=\"#\">".$lines[$i]."</a></li>";
    $j++;
      }      
    }
   }
 ?>  

The following javascript applies the onclick to each element:

 <script type="text/javascript">
    for (i = 0; i < <?php echo $j; ?>; i++) {
      iLINK = $("item"+i).get("title");
      iHTML = "<img src=\""+iLINK+"\" />";
      $("item"+i).setAttribute("onclick","$('photogal').innerHTML = " +iHTML);
       }
 </script>

When loading the page, the <li> elements are aesthetically fine. When inspecting the element I see the following (which appears to be correct):

When changing the last line of javascript to:

$("item"+i).setAttribute("onclick","$('photogal').innerHTML = iHTML");

the onclick works as expected, although all links cause the final image to show (because after the loop, iHTML ends up being whatever the last instance of iHTML was).

What is the problem in this code?

Share edited Jun 19, 2012 at 4:09 Derek 朕會功夫 94.5k45 gold badges198 silver badges253 bronze badges asked Jun 19, 2012 at 3:56 Christopher HinstorffChristopher Hinstorff 134 bronze badges 5
  • Stack Overflow does let users upload images. – Derek 朕會功夫 Commented Jun 19, 2012 at 3:58
  • @tekknolagi - Really? Didn't notice that. – Derek 朕會功夫 Commented Jun 19, 2012 at 3:59
  • Derek, it told me I couldn't because I was too new. – Christopher Hinstorff Commented Jun 19, 2012 at 4:00
  • @ChristopherHinstorff - Are you using jQuery in your code? setAttribute does not exists in jQuery objects. – Derek 朕會功夫 Commented Jun 19, 2012 at 4:01
  • @Derek looks like he's not - look at the use o .get(). It's either another library or something custom. – bfavaretto Commented Jun 19, 2012 at 4:04
Add a ment  | 

4 Answers 4

Reset to default 4

There are many problems in your code.

  1. Do not use the onclick attribute. Especially do not use javascript to manually write the onclick attribute when you can just assign to the event directly.
  2. $('photogal').innerHTML = <img...../> is wrong because it is incorrect JS syntax. Try wtiting that line directly into your JS and it will plain about <img.../> not being wrapped in quotes.
  3. if the $ is jQuery you dont need to use $('photogal').innerHTML =... you can just do $('photogal').html("<img.../>")
  4. the last thing you mention is because you need a closure in your loop to evaluate the value of i immediately. Look up closures to understand what I mean.

but I think your immediate problem is #2 above...

so. time for an actual MooTools answer (assumes MooTools 1.3+, ideally 1.4.5):

this is wrong on many levels:

<script type="text/javascript">
    for (i = 0; i < <?php echo $j; ?>; i++) {
      iLINK = $("item"+i).get("title");
      iHTML = "<img src=\""+iLINK+"\" />";
      $("item"+i).setAttribute("onclick","$('photogal').innerHTML = " +iHTML);
       }
</script>

unescaped html as string, invalid event assignment, inline js and so forth.

you want to assign a single event on the ul or li that contain your lis.

if your dom goes like this:

<ul class="imageNav">
    <li title="someimage.jpg"><a href='#'>someimage</a></li>
    <li title="someimage.jpg"><a href='#'>someimage</a></li>
    ...
</ul>

<div id="photogal"></div>

then you can have this separate in a single event bind outside of your page.

window.addEvent('domready', function() {
    // store the reference to target el
    var photogal = document.id('photogal');

    // delegate a single click event
    document.getElement('ul.imageNav').addEvent('click:relay(li > a)', function(event, el) {
        // stop the event.
        event && event.stop && event.stop();

        // have we got it cached?
        var img = el.retrieve('img');

        // if not, cache image
        if (!img) {            
            el.store('img', img = new Element('img', {
                src: el.getParent('li').get('title') // or el.get('text') -> faster
            }));
        }

        // empty target div and inject new image
        photogal.empty().adopt(img);
    });
});

see it working here: http://jsfiddle/dimitar/n6BZD/

the advantage is, total separation of concerns, DRY. no need for any element ids or whatever. you can put the src into a more semantic attribute like data-src or even as the href of the a itself so it degrades when no js.

so here is the semantic solution: http://jsfiddle/dimitar/n6BZD/1/

have fun

You are essentially saying the following:

$('photogal').innerHTML = <img src=\""+iLINK+"\" />

This is missing the quotes around your string to set the innerHTML to.

Update:

$("item"+i).setAttribute("onclick","$('photogal').innerHTML = " +iHTML);

to:

$("item"+i).setAttribute("onclick","$('photogal').innerHTML = '" + iHTML + "';");
$("item"+i).onclick = (function(iHtml) {
    return function() {
       $('photgal').innerHTML = iHTML;
    };
})(iHTML);
发布评论

评论列表(0)

  1. 暂无评论