我不是一個JavaScript大師,所以我需要一個簡單的代碼幫助。 我有一個按鈕可以清除輸入字段的值。如果輸入不爲空顯示按鈕
如果輸入字段爲空,我希望它(按鈕)隱藏,反之亦然(如果輸入字段中有文本,則可見)。
該解決方案可以是純JavaScript或jQuery,沒關係。越簡單越好。
我不是一個JavaScript大師,所以我需要一個簡單的代碼幫助。 我有一個按鈕可以清除輸入字段的值。如果輸入不爲空顯示按鈕
如果輸入字段爲空,我希望它(按鈕)隱藏,反之亦然(如果輸入字段中有文本,則可見)。
該解決方案可以是純JavaScript或jQuery,沒關係。越簡單越好。
if(!$('input').val()){
$('#button').hide();
}
else {
$('#button').show();
}
在它最簡單的形式;)
首先隱藏在頁面加載按鈕:
jQuery(document).ready(function() {
jQuery("#myButton").hide();
});
然後附加一個onChange
處理程序,它會隱藏按鈕,每當文本字段的內容是空的。否則,它顯示的按鈕:
jQuery("#myText").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery("#myButton").hide();
} else {
jQuery("#myButton").show();
}
});
您還需要清除輸入後隱藏按鈕:
jQuery("#myButton").click(function() {
jQuery("#myInput").val("");
jQuery(this).hide();
});
您可以使用$('selector').hide()
來隱藏的元素,$('selector').show()
再次顯示它。
更好的是,你可以使用$('selector').toggle()
讓它顯示和隱藏,沒有任何自定義邏輯。
$("input").keyup(function() {
if ($(this).val()) {
$("button").show();
}
else {
$("button").hide();
}
});
$("button").click(function() {
$("input").val('');
$(this).hide();
});
我們是否鼓勵或不鼓勵提供這樣的完整解決方案? (我既不在這裏,也不在那裏 - 只是好奇這是什麼姿態) –
@SergioTapia這不是一個真正的「完整」解決方案 - 我認爲這是相當枯燥的骨頭。它使用通用選擇器,並不關心輸入的值是什麼。它甚至不考慮最初隱藏按鈕(我會用css來做)。 –
我寧願使用「onchange」,因爲只有在文本被改變時才能觸發切換(可以按下很多按鈕而不實際觸發onchange事件)。 – Styxxy
做到不jQuery的(本質上是一回事別人已經做了,只是純粹的JS)。這很簡單,但我也添加了一些評論。
<body>
<input type="text" id="YourTextBox" value="" />
<input type="button" id="YourButton" value="Click Me" />
<script type="text/javascript">
var textBox = null;
var button = null;
var textBox_Change = function(e) {
// just calls the function that sets the visibility
button_SetVisibility();
};
var button_SetVisibility = function() {
// simply check if the visibility is set to 'visible' AND textbox hasn't been filled
// if it's already visibile and the text is blank, hide it
if((button.style.visibility === 'visible') && (textBox.value === '')) {
button.style.visibility = 'hidden';
} else {
// show it otherwise
button.style.visibility = 'visible';
}
};
var button_Click = function(e) {
// absolutely not required, just to add more to the sample
// this will set the textbox to empty and call the function that sets the visibility
textBox.value = '';
button_SetVisibility();
};
// wrap the calls inside anonymous function
(function() {
// define the references for the textbox and button here
textBox = document.getElementById("YourTextBox");
button = document.getElementById("YourButton");
// some browsers start it off with empty, so we force it to be visible, that's why I'll be using only chrome for now on...
if('' === button.style.visibility) { button.style.visibility = 'visible'; }
// assign the event handlers for the change and click event
textBox.onchange = textBox_Change;
button.onclick = button_Click;
// initialize calling the function to set the button visibility
button_SetVisibility();
})();
</script>
</body>
注意:我已經在IE9和Chrome中編寫並測試了這個,請確保在其他瀏覽器中測試它。另外,我添加了this fiddle,這樣您就可以看到它的工作。
你應該努力努力做自己。 –