jQuery $(this) on child selectors?



构建与Twitter的"关注/取消关注"按钮类似的设置,并且无法完全使其与jQuery一起使用。

到目前为止已完成; - 对单个已知ID进行jQuery,用于更新所需的所有详细信息<button>- 为服务器端逻辑提供支持的 API - 其他一切都在服务器端完美运行

想不通; - 如何将单个已知ID的功能扩展到多个未知ID

这是我为已知的单点工作的代码;

//Update Links
$("#api-follow-button").html(buttonText);
$("#api-follow-button").attr("currentState", currentState);

上面的代码被包装在一个函数中,其中包含由以下触发的大量其他代码;

$(document).on("click", "#api-follow-button", followButton());

这很完美,因为我知道 ID。挑战在于,当要更新的 ID 未知时,如何扩展它?

我已经使用$(this)测试了很多变体,但我没有得到任何工作。我敢肯定,我只是在这里错过了一些显而易见的东西。

因此,将此代码想象为示例;

<button id="button-idxxx">Text 1</button>
<button id="button-idxxx">Text 2</button>
<button id="button-idxxx">Text 3</button>

然后每当有人点击其中一个<button>,那么"文本X"就会变成其他内容

想法?

您提到的这个$(this)可能工作正常(尽管您没有发布相关代码)。

错误似乎出现在$(document).on("click", "#api-follow-button", followButton());中,followButton方法中应缺少()

所以试试

$(document).on('click', '[id^="button-id"]', followButton);

([id^="button-id"]选择器匹配具有以button-id文本开头的 id 属性的元素)

你的followButton应该是这样的

function followButton(e){
e.preventDefault();
// define buttonText and currentState here 
// unless they come from elsewhere
$(this)
.html(buttonText)
.attr("currentState", currentState);
}

(大声思考)您可能会使用链接文章中的属性开头为选择器。使用此选择器,您可以选择所有可能包含特定前缀的按钮(即button-id) 从您的示例中不知道元素的整个id

从属性开始-与选择器文档:

说明:选择具有指定属性且值正好以给定字符串开头的元素。

例如:

jQuery(function ($) {
	$(document).on('click', '[id^="button-id"]', function () {
	alert($(this).text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="button-id12345">
Text 1
</button>
<button type="button" id="button-id678910">
Text 2
</button>
<button type="button" id="button-id1112131415">
Text 3
</button>

谢谢大家。alert($(this).text());小提琴中的代码运行良好,但是当执行诸如更新页面上的文本之类的操作时,由于某种原因,这似乎不起作用。根据有用的信息进行一些摆弄,这是我想出的有效方法;

网页按钮

<button type="button" class="btn btn-lg btn-success" id="api-follow-button-uniqueID-xxx" currentState="NotFollowing">
<button type="button" class="btn btn-lg btn-success" id="api-follow-button-uniqueID-xxx" currentState="NotFollowing">
<button type="button" class="btn btn-lg btn-success" id="api-follow-button-uniqueID-xxx" currentState="NotFollowing">

j查询代码

$(document).ready(function () {
$(document).on('click', '[id^="api-follow-button"]', function followButton(e) {
e.preventDefault();
var currentState = $(this).attr("currentState");
//This line below ensures that you can then use the ID selector to update the relevant part of the HTML as needed, see note below
var buttonID = $(this).attr("id");

var buttonText = "";
var currentState = "";
buttonText = "Unfollow";
currentState = "Following";
//Update Links
//This part from comment above
$("button[id=" + buttonID + "]")
.html(buttonText)
.attr("currentState", currentState);
});
}
});
});

看起来现在一切都完成了。我从上面删除了一堆代码来简化事情

谢谢大家

最新更新