我正在尝试使用 js 的 onclick 事件在页面上生成动态内容,但控制台中出现错误“Uncaught SyntaxError: Unexpected identifier”html{% load static %}<head> <script type="text/javascript"> function myFunction() { // document.getElementById("demo").innerHTML = "Paragraph changed."; document.getElementById("demo").innerHTML = "{{ Malegender }}"; } </script> </head> <body> <div class="container mt-5"><h1>Gender</h1> <hr> <h5>{{ mygender.as_p }}</h5> <h1 id="demo">Hello</h1> <div class="container"> <button type="submit" name="gender_submit" class="btn btn-success" onclick="myFunction()">Confirm</button> </div> </div> </body>视图.pydef Gender(request): gender_selection = GenderForm() male_detail = MaleForm() Male = False print("Value of male",Male) if 'gender_submit' in request.POST: male_detail = MaleForm(data=request.POST) Male = True print("Value of male d",Male) print("Value of male a",Male) return render(request, 'Gender.html',{"mygender":gender_selection,"Malegender":male_detail})表格.pyclass MaleForm(forms.ModelForm): class Meta: model = GenderModel fields = ('genderMale','genderMale1','genderMale2','genderMale3','genderMale4')模型.pyfrom django.db import modelsfrom django.contrib.auth.models import Userfrom django.db.models.signals import post_savefrom django.dispatch import receiver# Create your models here.class GenderModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) gender_choice=(('Male','Male'),('Female','Female'),) gender = models.CharField(max_length=6,choices=gender_choice,null=True,) genderMale = models.BooleanField(default=False) genderMale1 = models.BooleanField(default=False) genderMale2 = models.BooleanField(default=False) genderMale3 = models.BooleanField(default=False) genderMale4 = models.BooleanField(default=False)当我单击按钮时,控制台上显示错误。当用户单击按钮时,我试图显示该内容
1 回答
猛跑小猪
TA贡献1858条经验 获得超8个赞
这个问题表明永远不要使用该onclick属性。相反,您可以尝试使用这样的事件侦听器:
<button type="submit" name="gender_submit" class="btn btn-success"
id="gender_submit_button">Confirm</button>
<script type="text/javascript">
function myFunction() {
document.getElementById("demo").innerHTML = "{{ Malegender }}";
}
document.getElementById('gender_submit_button').addEventListener('click', myFunction);
</script>
此外,请确保您的脚本放置后的按钮和演示。
添加回答
举报
0/150
提交
取消