我在我的JS函数中动态创建按钮,并将创建的按钮创建到DOM。
以下是代码:
var button = '<button id="btnStrView" type="button" onclick=' + parent.ExecuteCommand(item.cmdIndex) + ' class="button_air-medium">'+
+'<img id="streetView" class="miniToolbarContant" src="../stdicons/streetview-icon.png">'
+'</button>'
$( "#tdStrView" ).append(button);
当我在consle中显示creted动态按钮时,我看到了:
"<button id="btnStrView" type="button" onclick=undefined class="button_air-medium">NaN</button>"
似乎但未正确创建onclick未定义且img标记丢失。
知道我做错了什么吗?为什么图像按钮没有正确创建?
更新
我尝试在onclick事件中添加双引号:
onclick="' + parent.ExecuteCommand(item.cmdIndex) + '"
,创建的按钮为:
"<button id="btnStrView" type="button" onclick="undefined" class="button_air-medium">NaN</button>"
onclick仍未定义。
答案 0 :(得分:1)
您需要添加双引号.onclick将如下所示onclick="' + parent.ExecuteCommand(item.cmdIndex) + '"
$user = app('Dingo\Api\Auth\Auth')->user();
答案 1 :(得分:0)
// add double quotes in onClick and if you are getting NaN in place of image,
// it means that it is trying to add numbers. I'm not sure yet why this is happening, but
// to fix that, add extra string in second line. like this. and then console button.
var button = '<button id="btnStrView" type="button" onClick="alert(7)" class="button_air-medium">'+
+'' +'<img id="streetView" class="miniToolbarContant" src="../stdicons/streetview-icon.png">'
+'</button>'
答案 2 :(得分:0)
虽然这段代码更详细,但它更具可读性且不易出错。
const button = document.createElement('button');
button.id = 'btnStrView';
button.type = 'button';
button.className = 'button_air-medium';
button.addEventListener('click', event => {
parent.ExecuteCommand(item.cmdIndex);
});
const img = document.createElement('img');
img.id = 'streetView';
img.className = 'miniToolbarContant';
img.src = '../stdicons/streetview-icon.png';
button.appenChild(img);
$( "#tdStrView" ).append(button);
&#13;