我有以下 fiddle :http://jsfiddle.net/kmgj8ny9/
JQuery:
$(document).ready(function(){
$(".chosen-select").chosen();
$("body").on("focus", ".htLeft", function (e) {
//alert(this);
$(this).parent("div").parent("div").find("div:first-child").first().removeClass("setNormal").addClass("setBold");
});
$("body").on("focusout", ".htLeft", function (e) {
$(this).parent("div").parent("div").find("div:first-child").first().removeClass("setBold").addClass("setNormal");
});
});
如果文本区域获得焦点,则 Comments
标签为粗体,但如果下拉列表获得焦点,则 Issue
标签不是粗体。
下拉列表是一个 HTML 生成的 ASP.net 控件。
我该如何解决?
最佳答案
更新
基于提供的新 HTML,我调整了选择器以针对由所选插件创建的输入元素以及您的输入:
$(document).ready(function () {
$(".chosen-select").chosen();
$("body").on("focusin", ".htLeft, .chosen-search input", function (e) {
console.log(this);
$(this).closest(".section").find(".span_small:first").removeClass("setNormal").addClass("setBold");
});
$("body").on("focusout", ".htLeft, .chosen-search input", function (e) {
$(this).closest(".section").find(".span_small:first").removeClass("setBold").addClass("setNormal");
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/kmgj8ny9/12/
您还可以将事件处理程序合并为一个并检查 event.type
属性来决定您是 focusin
还是 focusout
并切换相应的类:
$("body").on("focusin focusout", ".htLeft, .chosen-search input", function (e) {
var focusin = e.type == "focusin";
$(this).closest(".section").find(".span_small:first").toggleClass("setNormal", !focusin).toggleClass("setBold", focusin);
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/kmgj8ny9/13/
通常你只需要一个类,你可以切换,而不是两个,因为默认样式应该与 setNormal
相同。这意味着您可以将其进一步缩短为:
例如
$("body").on("focusin focusout", ".htLeft, .chosen-search input", function (e) {
$(this).closest(".section").find(".span_small:first").toggleClass("setBold", e.type == "focusin");
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/kmgj8ny9/14/
原始答案
由于您用于下拉列表的插件,在下拉列表中获得焦点的控件不是 .htLeft
。该元素已被隐藏在其他元素中,以形成您所看到的“漂亮”控件。
试试这个作为快速修复:
$(document).ready(function () {
$(".chosen-select").chosen();
$("body").on("focusin", ".htLeft,:has(.htLeft)", function (e) {
//alert(this);
$(this).closest(".section").find("div:first-child").first().removeClass("setNormal").addClass("setBold");
});
$("body").on("focusout", ".htLeft,:has(.htLeft)", function (e) {
$(this).closest(".section").find("div:first-child").first().removeClass("setBold").addClass("setNormal");
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/kmgj8ny9/3/
通常我会在浏览器中查看 DOM,以查看插件创建了哪些元素并针对它们特定的内容。
注意:closest
总是比 parent("div").parent("div")
更可取,因为它处理 DOM 更改。
关于c# - 如何使用 JQuery 使以前的 DIV 文本加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29677189/