开发者

What is the minimum change to the last 3 lines of code that would make it work?

What is the minimum change to the last 3 lines of code that would make it work without adding or removing any lines of code?

<script>
function produceMessage(){
    var msg= 'This should print';
    return msg;
}

</script>

<div id="myDiv"> This should not print!</div>

<script>
    var element=document.开发者_StackOverflowgetElementById('myDiv').innerHTML;
    var message= produceMessage();
    element=message;</script>

For example this is not what I'm looking for since it combines the last three lines of code into one:

document.getElementById('myDiv').innerHTML= produceMessage();


from

<script>
    var element=document.getElementById('myDiv').innerHTML;
    var message=produceMessage();
    element=message;</script>

to

<script>
    var element=document.getElementById('myDiv');
    var message=produceMessage();
    element.innerHTML=message;</script>

.


The reason why your first one doesn't work is because you are assigning the text from the myDiv element to var element. Strings are primitive, so they are passed by value, meaning that a copy of the text from .innerHTML is copied into var element.

Rather than that, we want a reference to the HTML Element. Any non-primitive types are passed by reference by default in Javascript. To do that, we use

var element=document.getElementById('myDiv');

Now, var element points to the same object as the document.getElementById('myDiv'), rather than a different instance of the string from its innerHTML, meaning that when we modify the element.innerHTML, we also modify the same object as document.getElementById('myDiv').innerHTML, which happens to be the one on the DOM (web page), rather than a new and different copy of the string.


freedompeace definitely got it right, I just wanted to add why your code was failing.

Setting element = message doesn't do anything because you didn't end up doing anything with element. The variable element is not a reference to the innerHTML of 'myDiv', but rather is just a container holding the text " This should not print!". So, when you say element = message, you are just changing what the container 'element' holds instead of changing the innerHTML of 'myDiv'.


<script>
function produceMessage(){
    var msg= 'This should print';
    return msg;
}

</script>

<div id="myDiv"> This should not print!</div>

<script>

    var element=document.getElementById('myDiv');

    var message= produceMessage();

    element.innerHTML=message;
</script>

I Think that should work. Originally you were just getting a string and changing your copy of that string, not updating the objects property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜