JQuery modifica il testo in input
Domanda
Ho una configurazione della tabella come di seguito:
<table>
<tr>
<td class="url">
<a href="http://www.domainname.com/page1.html" />
</td>
</tr>
<tr>
<td class="url">
<a href="http://www.domainname.com/page2.html" />
</td>
</tr>
<tr>
<td class="url">
<a href="http://www.domainname.com/page3.html" />
</td>
</tr>
</table>
Fondamentalmente voglio che l'ancora cambi in una casella di testo contenente l'href quando si fa clic sul collegamento, di seguito sono riportati dei risultati di esempio:
<table>
<tr>
<td class="url">
<input type="text" value="http://www.domainname.com/page1.html" />
</td>
</tr>
<tr>
<td class="url">
<a href="http://www.domainname.com/page2.html" />
</td>
</tr>
<tr>
<td class="url">
<a href="http://www.domainname.com/page3.html" />
</td>
</tr>
</table>
Quando si fa clic su un altro tag di ancoraggio o la casella di testo è sfocata, tutte le caselle di testo tornano ad essere un ancoraggio e quella su cui si fa clic si trasforma in una casella di testo.
Soluzione
Questo è un inizio. Aggiungi un evento click ai link e un evento blur agli input usando live ()
.
$(function() {
$("td.url a").live("click", function() {
var parent = $(this).parent();
$(this).replaceWith("<input type='text' value='" + $(this).attr("href") + "'>"); //closing angle bracket added
parent.children(":text").focus();
return false;
});
$("td.url :text").live("blur", function() {
$(this).replaceWith("<a href='" + $(this).val() + "'>");
});
});
Detto questo, per questo genere di cose preferisco non eliminare elementi dal DOM in questo modo. Invece preferisco solo nascondere / mostrare gli elementi appropriati. Ad esempio:
<table>
<tr>
<td class="url">
<a href="http://www.domainname.com/page1.html" />
<input type="text">
</td>
</tr>
</table>
con:
td.url input { display: none; }
td.edit a { display: none; }
td.edit input { display: block; }
e
$(function() {
$("td.url a").click(function() {
var a = $(this);
a.next().val(a.attr("href")).focus();
a.parent().addClass("edit");
return false;
});
$("td.url :text").blur(function() {
var txt = $(this);
txt.prev().attr("href", txt.val());
txt.parent().removeClass("edit");
});
});
Altri suggerimenti
$(".url").click(function()
{
var link = $(this).find("a");
link.hide();
$(this).append("<input id'txtUrl' value" + link.attr("href") + " />");
});
Qualcosa del tipo:
$("td.url a").bind("click", function(){
var clickevent = arguments.callee;
$("td.url input").trigger("blur");
$(this).replaceWith("<input type='text' value='"+$(this).attr("href")+"'/>");
$("td.url input").bind("blur", function(){
$(this).replaceWith("<a href='"+$(this).val()+"' />");
$("td.url a").bind("click", clickevent);
});
});
totalmente non testato, ovviamente