简体   繁体   中英

Can this javascript code be rewritten in jQuery?

I use php to generate a table that has multiple links and divs like the one below, each with a unique id. Clicking the link shows the div. Can this be recoded with jQuery? The full code is pretty ugly with all of the backslashes and onclicks.

<a href = '#!' class = 'link' id = 'link".$id."' onclick = 'document.getElementById(\"box".$id."\").style.display = \"block\";'>click here</a>
<div class = 'box' id = 'box".$id."'>content here</div>

It's not JavaScript making it ugly (and jQuery being pretty); it's the lack of separation of concerns that makes it ugly. Isolate your JavaScript, and activate it by registering a listener, not directly as string of code on your HTML (something that is just Not Done any more by any serious JS user).

This is perfectly readable, despite being "just" JavaScript:

<a href='#!' class='link' id='link<?php echo $id; ?>'>click here</a>
<div class='box' id='box<?php echo $id; ?>'>content here</div>
<script>
  var link = document.getElementById('link<?php echo $id; ?>');
  var box = document.getElementById('box<?php echo $id; ?>');

  link.addEventListener('click', function(evt) {
    box.style.display = 'block';
  });
</script>

On the other hand, here is your original code with jQuery:

<a href = '#!' class = 'link' id = 'link".$id."' onclick = '$(\"#box".$id."\").css(\"display\", \"block\");'>click here</a>
<div class = 'box' id = 'box".$id."'>content here</div>

Still ugly.

This is one way, change the HTML structure to this:

<a href='#!' class='link' data-box='#box".$id."'>click here</a>
<div class='box' id='box".$id."'>content here</div>

Then, bind only one event listener (instead of one per id) to the .link class. Use this code in an external JS file:

$('.link').on('click', function (e) {
    e.preventDefault();
    var box = $(this).data('box');
    $(box).show();
});

try this one

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<a href = '#!' class = 'link' id = 'link<?php echo $id; ?>' >click here</a>
<div class = 'box' id = 'box<?php echo $id; ?>'>content here</div>
<script>    
$( ".link" ).click(function() {
    this.style.display = 'block';
    //this.style.display = 'none';
});
</script>

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