[英]How can I make this code work better?
最近,我問一個問題,關於操縱與jQuery的HTML選擇框,並已經得到了這真的簡短而親切的代碼作為一個答案。
$("#myselect").change(function (event) {
var o = $("#myselect option:selected"),
v=o.text(),
old = $("#myselect option:contains('name')"),
oldv = old.html();
oldv && old.html( oldv.replace('name: ', '') );
o.text('name: ' + v);
});
我有一個問題。 這段代碼不適用於多個類別,我似乎無法理解它是如何完成的。 所以,我做了一些明顯的改變:
$("select").change(function (event) {
var foo = $("select option:selected"),
bar = foo.text(),
cat = foo.parent().attr("label"),
old = $("select option:contains('" + cat + "')"),
oldbar = old.html();
oldbar && old.html( oldbar.replace(cat + ': ', '') );
foo.text(cat + ': ' + bar);
});
現在這適用於多個optgroups /類別,但導致了另一個錯誤。 那是一個更有問題的問題。
最后一個片段的問題是它使用當前類別的名稱來定位要翻轉的最后一個選定標簽。 相反,如何搜索“:”,(如果你在其中一個選項中有“:”,這將無法工作),然后替換字符串的那部分。
將第5行更改為:
, old = $("select option:contains(':')")
和第8行:
oldbar && old.html(oldbar.replace(oldbar.substr(0, oldbar.indexOf(':') + 2),''));
如果那不適合你,請告訴我!
編輯:作為事后的想法,您可以考慮添加此行
$('select').change();
同樣,在$(document).ready()事件中的某個地方,這樣當頁面首次呈現默認值時,會獲得您想要的前綴(我認為)。
我已經重命名了這些變量,因為用一個有意義的名字來命名你的變量和函數是一個很好的習慣,所以你可以在你的記憶中玩弄正在發生的事情。
$("select").change(function () {
// We immediately invoke this function we are in which itself returns a function;
// This lets us keep lastCat private (hidden) from the rest of our script,
// while still giving us access to it below (where we need it to remember the
// last category).
var lastCat;
return function (event) {
var selected = $("select option:selected"),
selectedText = selected.text(),
cat = selected.parent().attr("label");
if (lastCat) { // This won't exist the first time we run this
oldSelection = $("select option:contains('" + lastCat + ":')");
oldHTML = oldSelection.html();
oldHTML && oldSelection.html(oldHTML.replace(lastCat + ': ', ''));
}
selected.text(cat + ': ' + selectedText);
lastCat = cat; // Remember it for next time
};
}()); // Be sure to invoke our outer function (the "closure") immediately,
// so it will produce an event function to give to the change handler,
// which still has access to the variable lastCat inside
這是一個黑暗中的鏡頭。 乍一看,您似乎沒有保存以前的選擇,並且您正在使用在oldbar && old.html中觸發事件的選擇(oldbar.replace(cat +':','')); 線。 您需要在單獨的var中保存先前選擇的類別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.