我使用一个内容div来显示一个递归问题的结果-
通过从数字1开始并重复加5或乘以3,可以产生无限数量的新数字。你如何编写一个函数,在给定一个数字的情况下,试图找到一系列这样的加法和乘法来产生这个数字?例如,数字13可以通过先乘以3,然后两次加5来达到,而数字15根本不能达到。
我正在尝试找到解决方案,然后将其传递回reach()函数,该函数动态填充我的内容div:
<script>
function findTarget(target) {
function find(start,history) {
if (start === target)
return history;
else if (start > target)
return null;
else return ((find(start+5,"("+history+"+5)"))||(find(start*3,"("+history+"*3)")));
}
return find(1,"1");
}
function reach(x) {
var p=document.createElement('div');
var result = findTarget(parseInt(x));
var text = document.createTextNode(result);
p.appendChild(text);
p.setAttribute("class","limit");
document.getElementById('container').appendChild(p);
}
</script>
<body onLoad="reach(prompt('Enter a target number to reach'));">
<div id="container"></div>
</body>下面是我的容器和内容div的css
#container{ max-width:500px; margin:0 auto; width:500px;
background-color:#63DA85; word-break:break-all; }
.limit{ width:300px; max-width:300px; margin:auto; word-break:break-all;}当我执行这个脚本时,我确实得到了内容-但是它溢出了div -

我尝试在我的css中为容器和内容div使用word-break:break-all;,但只有在下面所示的reach函数中生成内容字符串时才有效
function reach(x) {
var p=document.createElement('div');
var text = document.createTextNode("a really long string like pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp");
p.appendChild(text);
//p.setAttribute("class","limit");
document.getElementById('container').appendChild(p);
}但是当内容被设置为来自其他函数(如findTarget )的返回值时,它就会中断。
我应该如何解决这个问题-我不想使用Jquery -只使用纯js解决方案
发布于 2015-08-20 17:13:02
为此,只需将以下css添加到您的#容器中
word-break: break-all;这允许在任意两个字母之间换行,请参见:
http://jsfiddle.net/us8qpvm0/
发布于 2015-08-20 17:13:21
尝试添加
word-break: break-all;添加到CSS中的#container类。
https://stackoverflow.com/questions/32113828
复制相似问题