我有一个模式(引导),在这里我试图填充用户点击的内容。我有多个产品,每次点击都应该加载产品细节的快速查看。
所以我的HTML看起来如下:
<li class="">
<a data-toggle="modal" v-on:click="loadProduct(<?=$pop->id?>, '<?=$language?>')" data-target="#productModal" title="Quick View" class="quick-view modal-view detail-link" href="#">
<span class="ti-plus"></span>
</a>
</li>我的模态HTML代码如下所示:
<div class="modal fade" id="productModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal__container" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span>×</span></button>
</div>
<div class="modal-body">
<div id="modalProduct" class="">
<div class="modalContentTrigger">
<div v-if="modalLoading" class="text-center" style="color:#ccc">
<i class="fa fa-circle-o-notch fa-spin fa-5x" aria-hidden="true"></i>
</div>
<div v-if="!modalLoading">
<div v-html="modalContent"></div>
</div>
</div>
</div>
</div>
</div>
</div>
我试图通过API调用并填充modalContent来实现modalContent。下面是我的vue函数与AXios的结合:
axios.post(vm.baseUrl + '/api/loadProduct', { productId: productId, language:language })
.then(function(response){
vm.modalContent = response.data;
vm.modalLoading = false;
});模型的内容是非常正确的,我在模型中看到HTML,但是不管javascript在里面什么,它都不起作用。例如,从API中获取的简单<div id='mydiv' onClick='alert("hello");'>test</div>不会在单击时触发。如果我将相同的代码放在一个静态HTML中,那么触发器单击就能很好地工作。
以上代码使用的是VUE2 2/AXIOS。
我甚至尝试过像这样使用Jquery来访问选择器,但是它不再工作了:
$("#mydiv").click(function(){alert('hello');});那么,我做错了什么,并且在模型中动态加载的内容不是java脚本友好的呢?
发布于 2018-05-01 09:45:40
TLDR
$("body").on("click","#mydiv", function(){alert('hello');});Vue的设计并不是为了这样使用。API返回原始HTML也不常见。Vue不会在模板中解析Javascript。实际上,如果您试图在任何Vue模板中包含一个脚本标记,就会得到以下错误:
模板应该只负责将状态映射到UI。避免在模板中放置带有副作用的标签,例如,因为它们不会被解析.
如果可以,避免使用v-html,更改API,使其只返回构建HTML所需的数据,而不是整个原始的HTML。使用Vue模板中的数据。
但是,如果不能,则可以继续尝试使用jquery侦听click事件。
$("#mydiv").click(function(){alert('hello');});可能无法工作,可能是因为在创建#mydiv之前执行了这一行。
这应该适用于你:
$("body").on("click","#mydiv", function(){alert('hello');});这将侦听body的单击事件,如果单击目标为#mydiv,则执行单击回调。
https://stackoverflow.com/questions/50113314
复制相似问题