如何使用 jquery 使用 'data-id' 属性更改 innerHtml 内容


How to change the innerHtml content using 'data-id' attribute using jquery?

<li data-id="528">
  <a title="LOGIN" class="dropdown-toggle" href="#">
          <i class="glyphicon glyphicon-user"></i>LOGIN</a>
  <div style="width: 350px;" data-width="350" data-class="menu-login-row">My other content</div>
</li>

我有这个html,我想通过数据ID更改内容,如下所示

<li data-id="528">
  <a title="LOGOUT" href="/logout">
          <i class="glyphicon glyphicon-user"></i>LOGOUT</a>
  <div style="width: 350px;" data-width="350" data-class="menu-login-row">My other content</div>
</li>

如果,请告诉我,这可能吗

谢谢。

是的,这是可能的。

喜欢这个

var a=$('li[data-id="528"]').find('a');
a.attr('href','/logout');
a.contents().filter(function() {
    return this.nodeType == 3
}).each(function(){
    this.textContent = this.textContent.replace('LOGIN','LOGOUT');
});

可以通过属性选择器获取元素,并使用 .html(( 修改内容:

$('[data-id="528"]').html('<a title="LOGOUT" href="/logout"><i class="glyphicon glyphicon-user"></i>LOGOUT</a><div style="width: 350px;" data-width="350" data-class="menu-login-row">My other content</div>')

实际上你可以通过.html((修改jquery元素的innerHtml

$(selector).html(whatEverYouWant);

试试吧。

var htmlData = '<a title="LOGOUT" href="/logout">';
    htmlData+= '<i class="glyphicon glyphicon-user"></i>LOGOUT</a>';
    htmlData+='<div style="width: 350px;" data-width="350" data-class="menu-login-row">My other content</div>';  

jQuery('li[data-id="528"]').html(htmlData);

你可以为此编写一行代码

$('li[data-id="528"]').find('a').attr("title","LOGOUT").attr("href","/logout").html('<i class="glyphicon glyphicon-user"></i>LOGOUT</a>');
相关文章: