javascript - 如何使用动态值更改引导切换?
问题描述
我正在执行更新操作,用户单击表中的元素,然后通过切换引导切换来更改值,但我不知道应该如何以及在哪里进行更改。
这是我的代码:
首先,用户可以点击元素,发送 ID:
<div class="btn fa-hover col-md-3 col-sm-4 col-xs-12" data-toggle="modal" onclick='wordEditModal({{key.id}})' data-target="#wordUpdateModal"><i class="fa fa-edit"></i>
然后,它调用wordEditModal
函数,向 django 端点发出请求:
url:'/socialanalyzer/dictionary_edit_modal/',
它返回单击的单词的极性,同时在 HTML 中打开一个模式,在这里我应该显示使用引导切换返回的值:
<form method="get" novalidate>
{% csrf_token %}
<fieldset>
<div class="form-group">
<!-- Now, this bootstrap toggle always display Positive value, I want that it display dynamically from the endpoint the value-->
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="polaridad">Polarity:</label>
<input id="toggle-polarity" checked type="checkbox" data-on="Positive" data-off="Negative" data-onstyle="success" data-offstyle="danger" data-width="100">
</div>
<br/><br/><br/>
<div class="modal-footer">
<input class="btn btn-success" type="submit" onclick='wordUpdate()' value="Guardar" />
<button type="button" class="btn btn-default" onclick="" data-dismiss="modal">Close</button>
</div>
</fieldset>
</form>
这是我的 ajax 函数:
function wordEditModal(wordId) {
$.ajax({
url:'/socialanalyzer/dictionary_edit_modal/',
type: 'GET',
data: {
word_id: wordId
},success: function(data) {
if (data.data.code==200) {
// This is what I tried, but didn't work
if (data.data.polarity.toLowerCase() == 'p'){
$('#toggle-polarity').bootstrapToggle('Positive')
}else {
$('#toggle-polarity').bootstrapToggle('Negative')
}
}else{
console.log('Error to load modal',data);
}
}
})
}
我的问题是,如何根据返回端点的值动态更改引导切换的值?
Positive和Negative是可能的值,所以如果用户点击一个带有负极性的单词,当模态打开时,bootstrap toggle 必须显示 Negative(危险)选项,如果单词是 Positive 那么 bootstrap toggle 必须显示积极(成功)选项。
我也尝试在 Ajax 函数中使用类似的东西,但没有奏效:
if (data.data.polarity.toLowerCase() == 'p'){
$("#toggle-polarity").val("success")
}else {
$("#toggle-polarity").val("danger")
}
任何帮助将不胜感激。
解决方案
按照@Chris G 的建议,这是我的解决方案:
function wordEditModal(wordId) {
$.ajax({
url:'/socialanalyzer/dictionary_edit_modal/',
type: 'GET',
data: {
word_id: wordId
},success: function(data) {
if (data.data.code==200) {
//console.log($('#toggle-polarity').bootstrapToggle()[0]['value'])
if (data.data.polarity.toLowerCase() == 'p'){
$('#toggle-polarity').bootstrapToggle('on')
//console.log('Is positive')
}else {
$('#toggle-polarity').bootstrapToggle('off')
//console.log('Is negative')
}
}else{
console.log('Error to load modal',data);
}
}
})
}
我希望这对其他人有用。
推荐阅读
- java - 如何使我的 SpringBoot 应用程序可以通过我的公共 IP 地址访问?
- laravel - Laravel 集合按日期获取唯一顺序
- java - 在测试 guava ImmutableList 行为时感到困惑
- node.js - 出现错误:未找到 - GET http://registry.npmjs.org/flutter_launcher_icons - 在 npm 安装中未找到
- tensorflow - Keras 自定义损失函数:tf.function-decorated 中的 ValueError
- python - 在 Tensorflow 中使用神经网络的奇怪决策边界
- rust - 如何使用 PalletB 从 PalletA 保存记录,而 PalletA 不知道节省基材和生锈的内部机制
- php - 为什么从数据库加载的 JSON 上的 PHP json_decode 不起作用?
- html - 应该使用什么数据类型将联系人号码插入 mysql?
- r - ggplot更改单日POSIXct变量的x轴起点