0

我需要在单选按钮之后添加一些 HTML,我想添加图像和功能,所以当我单击单选按钮时我会检查它。我会用我自己的selectRadioButton()功能检查单选按钮。

现有代码是,我无法编辑这部分:

<span class="ms-RadioText">
  <input id="idFirstRadioButton" type="radio" name="idFirstRadioButton" value="1" />
</span>

我的想法是为我的图像添加功能,是这样做的:

$("#idFirstRadioButton").after("Image 1:<br/><a href=\"javascript:selectRadioButton(\"idFirstRadioButton\")\"><img src=\"http://urltoimage/image.jpg\" border=\"0\"/></a>");

但是当我使用这段代码时,我页面的 HTML 是这样的:

<span class="ms-RadioText">
  <input id="idFirstRadioButton" type="radio" name="idFirstRadioButton" value="1" /> Image 1:<br/><a href="javascript:selectRadioButton(" shape="" idFirstRadioButton?)?=""><IMG src="http://urltoimage/image.jpg" border=0></a>
</span>

他正在添加 "shape="" idFirstRadioButton?)?="""

正确的代码应该是:

<span class="ms-RadioText">
   <input id="idFirstRadioButton" type="radio" name="idFirstRadioButton" value="1" /> Image 1:<br/><a href="javascript:selectRadioButton("idFirstRadioButton")><IMG src="http://urltoimage/image.jpg" border=0></a>
</span>

我已经尝试过 with ', with \", 两者的组合, with a variable, ...

$("#idFirstRadioButton").after("Image 1:<br/><a href=\"javascript:selectRadioButton(\"idFirstRadioButton\")\"><img src=\"http://urltoimage/image.jpg\" border=\"0\"/></a>");
$("#idFirstRadioButton").after('Image 1:<br/><a href="javascript:selectRadioButton(\"idFirstRadioButton\")"><img src="http://urltoimage/image.jpg" border="0"/></a>');
$("#idFirstRadioButton").after('Image 1:<br/><a href="javascript:selectRadioButton("' + VARidFirstRadioButton + '")"><img src="http://urltoimage/image.jpg" border="0"/></a>');

我做错了什么或者我应该使用什么代码?

4

3 回答 3

2

您应该在.after字符串中使用不同的引号,因为它们是必需的。例如:

$("#idFirstRadioButton").after("Image 1:<br/><a href=\"javascript:selectRadioButton('idFirstRadioButton')\"><img src=\"http://urltoimage/image.jpg\" border=\"0\"/></a>");

这是结果:

<a href="javascript:selectRadioButton('idFirstRadioButton')"><img src="http://urltoimage/image.jpg" border="0"></a>

但是,这仅在您别无选择的情况下。正如@CBroe 提到的,您应该尽量不要在附加的html 中绑定事件处理程序,而是尝试使用正确的方式处理它们。@Dan O 提供的示例似乎是您应该寻找的东西。

于 2017-02-06T12:11:15.820 回答
1

您做错的是使用 HTML 字符串而不是自己构造和附加元素,这(除了潜在的安全问题)可能会导致您在此处看到的那种令人困惑和烦人的行为。你想要这样的东西:

var myImg = $("<img/>");
myImg.attr("src", "http://urltoimage/image.jpg");
myImg.on("click", function(e) {
  selectRadioButton("idFirstRadioButton");
});
$("#idFirstRadioButton").after(myImg);
于 2017-02-06T12:10:18.357 回答
0

当你有超过 1 层的深度"或者'你需要插入它们或逃离它们时。

最后一个应该是正确的,除了你一直使用 "inside 而不是逃避它们或交替它们。

正确的应该是:

$("#idFirstRadioButton").after('Image 1:<br/><a href="javascript:selectRadioButton(\'' + VARidFirstRadioButton + '\')"><img src="http://urltoimage/image.jpg" border="0"/></a>');

所以我们从后面的单引号开始,然后是href的双引号,然后我们为selectRadioButton内部转义一个单引号,然后一个单引号退出字符串并转储var,然后回到字符串内部并继续上。 小提琴

注意:请记住声明您的 var "VARidFirstRadioButton" 是 shape of错误的。

于 2017-02-06T12:17:42.480 回答