gpt4 book ai didi

javascript - 如何使用 JQuery 复选框禁用输入

转载 作者:行者123 更新时间:2023-12-03 02:33:32 25 4
gpt4 key购买 nike

我有一个网页,旨在简化为另一个程序(Ren'Py)编写代码的过程,我用一个按钮添加了 3 个输入(复选框、文本、文本)。现在我想禁用第一个输入,并且仅在选中复选框时启用。

我已经看过很多其他这样的问题,但似乎没有一个有帮助,我对静态运行中工作的代码进行了修改,所以代码已经在那里了。但它应该适用于所有这些,即使添加了新的。

var i = 0 //the variable is for a later cause, doesn't affect this, isn't implemented yet
function addDialogue() {
++i
var poseLine = '<input type="checkbox" id="poseBox' + i + '" class="pose" />\n<input id="pose' + i + '" />'
var text = '<input id="text' + i + '" >'
var breaker = '<br />'
var line = poseLine + text + breaker
$( "#dialogeAndCode" ).append( line )
}

function main () {
console.log( "JQuery has loaded" )
$( ":checkbox" ).change( function() {
if ( $( this ).hasClass( "pose" ) ) {
$( this ).next().prop( "disabled", !$( this ).is( ':checked' ) );
}
} );
}

$( document ).ready( main );
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<input type="button" id="buttonAddText" value="Add a dialoge line" onclick="addDialogue();">
<br />
<div id="dialogeAndCode">
</div>

这是静态运行(JS Fiddle):https://jsfiddle.net/DiamondFrost/1dsdd2Lx/

最佳答案

在您设置事件处理程序时,复选框不存在,因此请在文档上进行设置并使用 JQuery's event delegation 以便将来创建的复选框将被选中。

此外,JQuery 不久前已弃用 .change() 方法,并表示仅使用 .on() 方法进行所有事件绑定(bind)。

最后,将文本字段设置为默认禁用,因为默认情况下不会选中您的复选框。

var i = 0 //the variable is for a later cause, doesn't affect this, isn't implemented yet
function addDialogue() {
++i
// Set the textbox to be disabled by default
var poseLine = '<input type="checkbox" id="poseBox' + i + '" class="pose">\n<input disabled id="pose' + i + '">'
var text = '<input id="text' + i + '" >'
var breaker = '<br />'
var line = poseLine + text + breaker
$( "#dialogeAndCode" ).append( line )
}

function main () {
console.log( "JQuery has loaded" )

// Set up the event on the document, but trigger it if the source of it
// was a checkbox
$(document).on("change", "input[type=checkbox]", function() {
if ( $( this ).hasClass( "pose" ) ) {
$( this ).next().prop( "disabled", !$( this ).is( ':checked' ) );
}
} );
}

$( document ).ready( main );
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<input type="button" id="buttonAddText" value="Add a dialoge line" onclick="addDialogue();">
<br />
<div id="dialogeAndCode">
</div>

关于javascript - 如何使用 JQuery 复选框禁用输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48633344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com