2013-06-26 27 views
0

我有未知數量的未知ID的輸入框。我希望能夠點擊一個輸入框,並有一個修剪版本的值填充div。修改的輸入值顯示在div中

JSFiddle

我的代碼如預期一旦輸入字段編輯工作的,但我想有第一次點擊所顯示的值/集中

這是我寫的JS函數。

JS

$('input').each(function() { 
     var $tthis = $(this), 
      defaultValue = $tthis.val(); 

defaultValue = defaultValue.substring(keyed.indexOf("|") + 1); 
defaultValue = defaultValue.substring(0, defaultValue.length - 2) 
     $("#target").html(defaultValue);  

}); 

HTML

<input 
id='thistext$index' 
type='text' 
onclick='this.select();' 
onfocus=" 
document.getElementById('show_hide').style.display='block'; 
document.getElementById('show_hide2').innerHTML = 'Copy this text into the wiki, it will display as: ';" 
onblur="document.getElementById('show_hide').style.display='none';" value='&#91&#91;http://www.example.com/$dirArray[$index]&#124;$dirArray[$index]&#93;&#93;' /> 

<div id='show_hide'> 
    <div id='show_hide2'> 
    </div> 
    <div id='target'> 
    </div> 
</div> 

回答

1

我重組你的代碼有點從第一小提琴。 我拋出所有內聯的JavaScript,它的處理程序,onFocus, onBlur, onClick和jQuery替代品,我想我得到了你想要的。

我用jQuery的on()方法做了很多清理HTML的相同的事情。 然後我用show()中的一個函數來觸發一些其他功能。 這可能會更程序化,但我認爲它很好,很乾淨。

最後,我提取出修剪和子串到它自己的函數,以便您稍後可以重用它。

A fiddle here和下面的代碼:

$('input').on('click', function() { 
    var $input = $(this); 
    $('#show_hide').show(function(){ 
     $('#show_hide2').text('Copy this text into the wiki, it will display as:'); 
     var text = trimInputValue($input); 
     $('#target').text(text); 
    }); 
}); 

function trimInputValue($input) { 
    var text = $input.val(); 
    text = text.substring(text.indexOf("|") + 1); 
    text = text.substring(0, text.length - 2); 
    return text; 
} 

$('input').on('focusout', function() { 
    $('#show_hide').hide(); 
}); 

現在你可能想知道您select()去了。 不要擔心,只需將其包含在您的on('click', function(){ select(); });中,即可執行。

+0

這個。是。真棒! - 謝謝。 – redditor