为动态创建的嵌套div添加onclick href

时间:2016-12-25 15:44:49

标签: javascript html css

在这种情况下,我无法逃避我认为的报价。

我从最后一天开始尝试

var obj = deals[i]; 
var1 = "my var"
var url =  "index.html?name="+obj['a']+"&user="+var1+"+obj['a'];

var div = document.createElement('div');
div.innerHTML = '<div style="width: 100%; overflow: hidden" >' +
'<div style="width: 10%; float: left;" >' +
'<div><img src="assets/img/userimg.png" style="height: 35;margin-left: 10; margin-right: 5px;"/></div> <div id="toro" style="color: black">' +  obj['a'] + '</div>' +
 '</div>' +
 '<div style="margin-left: 25%;">' +
 '<div style="margin-top: 7;font-weight: bold; color: black">' +obj['b']+'</div> <div style="color: black" >' + '</div><div style="float: right" id="time">'+'</div></div></div> '+'<hr class=\"hr-clas-low\" />';

  document.getElementById('deals').appendChild(div)

如何将url作为onclick href url添加到新创建的div?

好的我再次重写这个问题,以表达我被困的地方

var obj = deals[i]; 
var1 = "my var"
 var url =  "index.html?name="+obj['a']+"&user="+var1+"+obj['a'];




var div = document.createElement('div');
div.innerHTML = '<div style="width: 100%; overflow: hidden"    onclick="location.href='+url+'>' +
'<div style="width: 10%; float: left;" >' +
'<div><img src="assets/img/userimg.png" style="height: 35;margin-left:    10; margin-right: 5px;"/></div> <div id="toro" style="color: black">' +        obj['a'] + '</div>' +
'</div>' +
'<div style="margin-left: 25%;">' +
'<div style="margin-top: 7;font-weight: bold; color: black">'       +obj['b']+'</div> <div style="color: black" >' + '</div><div style="float:       right" id="time">'+'</div></div></div> '+'<hr class=\"hr-clas-low\" />';

document.getElementById('deals').appendChild(div)

我补充说     的的onclick =“location.href = '+ URL +'     对外部div但它不起作用?

1 个答案:

答案 0 :(得分:0)

我在这段代码中看到的唯一错误是在第一行的三行中:

var obj = deals[i]; 
var1 = "my var"
 var url =  "index.html?name="+obj['a']+"&user="+var1+"+obj['a'];

我认为应该是:

var obj = deals[i]; 
var1 = "my var";
var url =  "index.html?name="+obj['a']+"&user="+var1+obj['a'];

然后:

div.innerHTML = '<div style="width: 100%; overflow: hidden" onclick="location.href='+url+'"><div style="width: 10%; float: left;" ><div><img src="assets/img/userimg.png" style="height: 35;margin-left: 10; margin-right: 5px;"/></div><div id="toro" style="color: black">'+obj['a']'+</div></div><div style="margin-left: 25%;"><div style="margin-top: 7;font-weight: bold; color: black">'+obj['b']+'</div><div style="color: black" ></div><div style="float: right" id="time"></div></div></div><hr class="hr-clas-low" />'

应该可以正常工作