我想更改我的按钮文本,如下所示,我有两个选择选项,草稿和发布。当我选择草稿选项时,必须更改按钮文本。但是如果没有刷新页面我就无法改变它。我怎么能这样做?
<body>
<button id="button" value=""></button>
<select name="select" id="draftOrPublish">
<option value="0">Draft</option>
<option value="1">Publish</option>
</select>
</body>
<script>
var draftOrPublish = $('select#draftOrPublish').val();
if (draftOrPublish == 0) {
$('button#button').text('Save as Draft')
} else if (draftOrPublish == 1) {
$('button#button').text('Publish')
}
</script>
答案 0 :(得分:2)
您必须将代码放在$(document).ready
和$( 'select#draftOrPublish' ).change
$(document).ready
- 在文档“准备就绪”之前,无法安全地操作页面。
$( 'select#draftOrPublish' ).change
- 将事件处理程序绑定到“更改”JavaScript事件,或在元素上触发该事件。
$(document).ready(function(){
$( 'select#draftOrPublish' ).change(function(){
var draftOrPublish = $('select#draftOrPublish').val();
if (draftOrPublish == 0) {
$('button#button').text('Save as Draft')
} else if (draftOrPublish == 1) {
$('button#button').text('Publish')
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button id="button" value=""></button>
<select name="select" id="draftOrPublish">
<option value="0">Draft</option>
<option value="1">Publish</option>
</select>
答案 1 :(得分:1)
您需要将此功能纳入函数,以评估选择的值是否已更改。这称为事件,您需要将事件侦听器附加到<select>
标记,以便您可以应用事件处理程序来更改按钮的文本。 jQuery有.change()
函数可用于收听<select>
标记
var draftOrPublish = $('#draftOrPublish').val();
if (draftOrPublish == 0) {
$('#button').text('Save as Draft')
} else if (draftOrPublish == 1) {
$('#button').text('Publish')
}
$('#draftOrPublish').change(function () {
var draftOrPublish = $('#draftOrPublish').val();
console.log(draftOrPublish)
if (draftOrPublish == 0) {
$('#button').text('Save as Draft')
} else if (draftOrPublish == 1) {
$('#button').text('Publish')
}
})
答案 2 :(得分:0)
您可以在jQuery中使用By.xpath(".//a[contains(@href,'products')]");
动态更改文本和值,而无需加载页面。
change()
&#13;
$('#draftPublish').change(function () {
var draftPublish = $('#draftPublish').val();
if (draftPublish === "0") {
$('#btn').text('Save as Draft');
$('#btn').val('draft');
} else if (draftPublish === "1") {
$('#btn').text('Publish');
$('#btn').val('publish');
}
});
&#13;