如何设置父ul中第一个元素的HTML

我正在页面上做一个简单的JQuery AJAX更新,我只想用服务器返回的结果更新第一个列表元素(它只是一个数字)。

我的HTML有点像这样(psuedo):

当用户点击Push UpPush Down ,我会对服务器进行AJAX更新,并返回一个数字。 服务器知道要更新哪个产品(我排除了这个代码,因为这个代码不需要)我想用这个数字更新第一个li 。 我试过这段代码,但似乎更新了第二个li 。 也就是说,它用数字更新“ Push Upli 。 我不明白为什么?

 $(this).parents("ul.product-controls li:first").html(result); 

result只是从服务器发回的号码。

完整的JQuery代码:

  $('a[name="PushUp"]').on('click', function(event) { $.ajax({ context: this, type: "post", url: "page.cfm", data: $.param(data), dataType: "json", beforeSend: function() { }, success: function(result) { $(this).parents("ul.product-controls li:first").html(result); }, complete: function() {}, error: function(a) { alert("An error has occured. Please try again."); } }); event.preventDefault(); }); 

您可以这样使用,使用closest()获取父级ul并找到li:first以获得ul第一个li

注意 : – 假设$(this)是锚标记的实例。

 $(this).closest("ul.product-controls").find("li:first").html(result); 

修改了ajax调用 –

 $('a[name="PushUp"]').on('click', function(event) { var $this = $(this); $.ajax({ context: $this, type: "post", url: "page.cfm", data: $.param(data), dataType: "json", beforeSend: function() { }, success: function(result) { $this.closest("ul.product-controls").find("li:first").html(result); }, complete: function() {}, error: function(a) { alert("An error has occured. Please try again."); } }); event.preventDefault(); }); 

问题是你的parents()没有使用正确的选择器, li不是li的父级。 您可以使用parents('ul')然后找到第一个或只是

  $(this).parent().find('li:first-child').html(result); 

编辑以匹配范围

 $('a[name="PushUp"]').on('click', function(event) { var $this = $(this); $.ajax({ ... success:function(result){ $this.parent().find('li:first-child').html(result); } }); }); 

有些如何使用ClassID执行此操作:

 $(".product-controls").children().eq(0).html(result); 

如果你使用ajax, this应该是ajax请求的对象而不是超链接。 您可以使用console.log(this)来检查这console.log(this) ,然后您会发现这涉及哪个DOM元素

样品

尝试使用:first-child选择器

 $("ul.product-controls li:first-child").html(result); 

这将有效,最接近父母。 你需要先找到给定类的第一个ul,然后在里面寻找一个孩子:)

 $(this).closest("ul.product-controls").find("li:first").html(result); 

你可以这样做:

  

你必须得到父母,然后去第一个李,这是一个好方法

 $(this).parents('ul').find("li:first").html(result); 

更新:

这是一个完整的代码:;)

 $('li.inner a').click(function(){ var myUL=$(this).parent().parent(); myUL.find("li:first").html("5"); }); 

要么

 $('li.inner a').click(function(){ $('ul.product-controls').find("li:first").html("for example: 5"); });