开发者

Element ID

开发者 https://www.devze.com 2023-01-20 08:28 出处:网络
I\'m trying my best to make my jQuery / AJAX scripts, but sometimes I run into some problems, like right now, so I\'m seeking some help!

I'm trying my best to make my jQuery / AJAX scripts, but sometimes I run into some problems, like right now, so I'm seeking some help!

On a game page of my website, in the comment box, you find a little "Like (0)" link right there, and when you click, well it actually adds +1 to the comment, without any page reload.

On the PHP side, all goes well, but in the javascript part, I got trouble with the ID's. The original code I had contained this:

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("like").innerHTML=xmlhttp.responseText;
    }
  }

Where I'm having issues is the document.getElementById("like") part. Since I have many comments, I deceided to give them a different ID to solve the problem, so comment 1 will have

<span id="like1">The +like stu开发者_开发问答ff here</span> 

and so on (like2, like3, etc)

But in my JS code (I already did some Actionscript, and was using the evenement.currentTarget) I cant figure out how to do it. (So if I click like10, it will update the like10 span box.)

Any help would be greatly appreciated!

I dont know if I'm clear enough, but thanks anyways!


Here's how you do it:

  function getComment(i)
  {
    ...
    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
         document.getElementById("like"+i).innerHTML=xmlhttp.responseText;
      }
    }
  }


Something like this should work:

function handle_click(event)
{
  var evt = event || window.event; // IE doesn't pass along an event object
  var target = evt.target || evt.srcElement; // IE and W3C differ on what property to use
  var id_to_update = ... // figure out which ID needs updating (perhaps based on target)

  var request = setup_xhr(); // dummy function that sets up an XHR object
  request.open(...);
  request.onreadystatechange = function()
  {
    if (request.readyState == 4 && request.status == 200)
    {
      update_like(id_to_update, request.responseText)
    }
  }
}

function update_like(target, new_value)
{
  document.getElementById(target).innerHTML = new_value;
}

document.getElementById('[id of element]').addEventListener('click', handle_click); // only covers the W3C event model, but you get the idea

When the event listener function sets up the AJAX request, you can have it specify which element will be updated, so when it completes it updates the correct one.


Since you say you are using jQuery, sounds like you should be using it's $.ajax and .bind() functions instead of native js.

0

精彩评论

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

关注公众号