如果先前的条件为真,我正在尝试执行一段代码。但是我很难这么做。
我要执行的代码是这个。
$(document).ready(function() {
$('.btn-addtocart').click(function() {
$('#overlay').show();
});
$('#close').click(function() {
$('#overlay').fadeOut(300);
});
});
如果"input:file"
为真,我想使其执行。目前,我有另一段代码可以禁用“添加到购物车”按钮,并在输入文件为true时启用它,但是这对我的用户来说似乎很混乱且效率低下。
我目前使用此按钮来禁用添加到购物车按钮,以使点击时不会弹出叠加层。但是,我希望这样做,以便您可以单击按钮,除非有文件输入,否则什么也不会发生。
$(document).ready(
function() {
var inputs = [
$("input:file"),
$("input[name='properties[Background]']"),
$("input[name='properties[Shape]']"),
$("input[name='properties[E-Mail]']")
];
$("input").change(
function () {
var enableCheckoutButton = inputs.reduce(
function (enabled, input) {
return enabled && input.val();
},
true
);
$('#checkoutbtn').prop('disabled', !enableCheckoutButton);
}
);
}
);
上传按钮的HTML
<div class="form-prepend">
<div class="custom_upload_field">
<label class="custom-file-btn">
<input class="uploadit" id="custom_photo" type="file" accept="image/*" name="properties[Upload]" onchange="readURL(this);" required="">
Upload
</label>
<div class="preview_right">
<img id="preview" src="https://cdn.shopify.com/s/files/1/0268/3410/8509/files/upload_preview.png?1271" alt="preview image">
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
</div>
</div>
<div class="tt-wrapper product-information-buttons"><a data-toggle="modal" data-target="#modalProductInfo" href="#"><span class="icon-f-09"></span> Size guide</a><a data-toggle="modal" data-target="#modalProductInfo-02" href="#"><span class="icon-f-44"></span> Shipping</a></div></div>
您可以将所有input
元素存储在array
中,遍历所有元素,然后将event listener
与要运行的function
附加在一起。下面的代码段是概念证明:
HTML:
<div>
<input class='input-elements' type='file' />
<input class='input-elements' type='text' />
</div>
JavaScript:
const inputs = document.querySelectorAll('.input-elements')
const customFunction = () => {
console.log('Running the customFunction!')
}
inputs.forEach((el) => {
if(el.type === 'file'){
el.addEventListener('click', customFunction())
}
})