简体   繁体   English

如何使用 AJAX 更新 href ID

[英]How to update href ID using AJAX

I have a following link in my code:我的代码中有以下链接:

<li onclick="loadNewPage('test')"><a href="#">Link</a></li>

When the user click this link, I will use xmlHttpRequest to update some content in a DIV on the webpage.当用户点击此链接时,我将使用 xmlHttpRequest 来更新网页上某个 DIV 中的一些内容。

But at the same time, when the user click the link, I want to add an id, so that the state of the button can be changed using CSS.但同时,当用户点击链接的时候,我想添加一个id,这样就可以使用CSS改变按钮的state。 (note the "id" being added to the link) (注意添加到链接的“id”)

<li onclick="loadNewPage('test')"><a href="#" id="current">Link</a></li>

At the same time, if these is any other link on the page with the id "current" I want to remove that ID.同时,如果这些是页面上 ID 为“当前”的任何其他链接,我想删除该 ID。

Is this possible?这可能吗? How to do this?这个怎么做?

It is good practice that every element that you want to handle in your HTML has its own, fixed ID.您希望在 HTML 中处理的每个元素都有自己的固定 ID,这是一种很好的做法。

I would suggest that your put an id when creating the page.我建议您在创建页面时输入一个 id。 If you want to change something, you may change the class of the element instead of the ID.如果要更改某些内容,可以更改元素的 class 而不是 ID。

Initial:最初的:

<li onclick="loadNewPage('test')"><a href="#" id="section_1">Link</a></li>

After clicking:点击后:

<li onclick="loadNewPage('test')"><a href="#" id="section_1" class="selected">Link</a></li>

JQuery (amongst other libraries) provide useful methods to retrieve elements of a given class, in order to change them. JQuery(在其他库中)提供了有用的方法来检索给定 class 的元素,以便更改它们。

Why not have为什么没有

<li onclick="loadNewPage(this,'test')"><a href="#">Link</a></li>

and

function loadNewPage(theLi,sometext) {
  theLi.className=theLi.className==""?"clicked":"";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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