简体   繁体   English

单击图像时如何更改innerHTML内容?

[英]How can i change the innerHTML content when clicking on an image?

I'm quite new in coding, trying to educate myself because i'm interested. 我在编码方面还很陌生,因为我很感兴趣,所以想自学。 So, sorry if it's going to be a bit dumb question or not so specific or not really correct... 所以,很抱歉,如果这将是一个愚蠢的问题,或者不是那么具体或不正确...

On my "practicing site" i'm having some navigation links, which are referring to different innerHTML contents (like different pages). 在我的“练习站点”上,我有一些导航链接,它们指向不同的innerHTML内容(例如不同的页面)。 I used the 'onClick' event to make them show up, for example like this: 我使用了'onClick'事件使它们显示出来,例如:

<div class="nav" onClick="changeNavigation('a')">menu</div>

It works with texts perfectly, but my problem is that i don't know how to make the same with an image. 它可以完美地处理文本,但是我的问题是我不知道如何对图像进行处理。 So when i click on the image, i want to be redirected to that innerHTML page, like i did it with the text based button. 因此,当我单击图像时,我想重定向到该innerHTML页面,就像使用基于文本的按钮那样。 I tried to do it like these two ways, but none of them worked. 我试图通过这两种方式来做到这一点,但是没有一个起作用。

<img src="picture.png" onClick="changeNavigation('a')" />

<div onClick="changeNavigation('a')"><img src="picture.png"></div>

Is it possible to make this with an image and the 'onClick' event? 是否可以通过图片和“ onClick”事件来做到这一点? Or how else can i make this work? 或者我还能怎么做?

By the way this is my script to make innerHTML show up: 顺便说一下,这是我的脚本,可以显示innerHTML:

<script>
    function changeNavigation(id) {
        document.getElementById('main').innerHTML = document.getElementById(id).innerHTML
    }
</script>

I also tried to add my image an id that says 'main' like in the script this way, but with no result. 我还尝试通过这种方式向图像添加一个ID为“ main”的ID,但没有结果。

<img id="main" onClick="changeNavigation('f')" src="picture.png" />

Can you help me please? 你能帮我吗? I would appreciate any answer, because i already searched about this and i didn't find anything that could've helped solve my problem and i'm really stuck right now. 我希望得到任何答案,因为我已经搜索了这个问题,但没有找到任何可以帮助解决我的问题的方法,而且我现在真的很困。

(Sorry if my english isn't the best, it's not my native language.) (很抱歉,如果我的英语不是最好的话,那不是我的母语。)

I have updated my answer to what you want. 我已将您的答案更新为我的答案。 You need to the divs id you want to display as a parameter to the function you use for onclick. 您需要输入要作为onclick函数所用参数的divs ID。 A sample is below. 下面是一个示例。

 var divs = ["Menu1", "Menu2", "Menu3", "Menu4"]; var visibleDivId = null; function toggleVisibility(divId) { if(visibleDivId === divId) { visibleDivId = null; } else { visibleDivId = divId; } hideNonVisibleDivs(); } function hideNonVisibleDivs() { var i, divId, div; for(i = 0; i < divs.length; i++) { divId = divs[i]; div = document.getElementById(divId); if(visibleDivId === divId) { div.style.display = "block"; } else { div.style.display = "none"; } } } 
 .main_div{text-align:center; background: #00C492; padding:20px; width: 400px;} .inner_div{background: #fff; margin-top:20px; height: 100px;} .buttons a{font-size: 16px;} .buttons a:hover{cursor:pointer; font-size: 16px;} img {cursor:pointer} 
 <div class="main_div"> <div class="buttons"> <img src="http://www.clker.com/cliparts/J/g/2/D/p/I/one-hi.png" width="50px" onclick="toggleVisibility('Menu1');"> <img src="http://www.clker.com/cliparts/E/x/J/x/m/z/blue-number-two-hi.png" width="50px" onclick="toggleVisibility('Menu2');"> <img src="http://www.clker.com/cliparts/L/H/T/b/g/N/three-md.png" width="50px" onclick="toggleVisibility('Menu3');"> <img src="http://www.clker.com/cliparts/v/G/G/A/D/s/four-md.png" width="50px" onclick="toggleVisibility('Menu4');"> </div> <div class="inner_div"> <div id="Menu1">I'm container one</div> <div id="Menu2" style="display: none;">I'm container two</div> <div id="Menu3" style="display: none;">I'm container three</div> <div id="Menu4" style="display: none;">I'm container four</div> </div> </div> 

You can just keep all of the sections as children of #main , and selectively show them when the section button in clicked. 您可以将所有部分保留为#main#main ,并在单击部分按钮时有选择地显示它们。 Eg, 例如,

HTML 的HTML

<nav>
  <button type="button" data-index=0>Show one</button>
    <button type="button" data-index=1>Show two</button>
    <button type="button" data-index=2>Show three</button>
</nav>
<main id="main">
  <section>One</section>
  <section class="hidden">Two</section>
  <section class="hidden">Three</section>
</main>

CSS 的CSS

.hidden {
  display: none;
}

JavaScript 的JavaScript

const buttons = Array.from(document.querySelectorAll('button'));
const contentBlocks = Array.from(document.querySelectorAll('section'));

function hideSections (arr) {
  arr.forEach(a => {
    a.classList.add('hidden');
  });
}

function showSection (index, sections) {
  // Just a basic check, not exhaustive by any stretch
  if (index !== undefined && sections !== undefined) {
    hideSections(sections);
    sections[index].classList.remove('hidden');
  }
}

buttons.forEach(button => {
  button.addEventListener('click', () => {
    const contentBlocks = Array.from(document.querySelectorAll('section'));
    const index = button.getAttribute('data-index');
    showSection(index, contentBlocks);
  });
});

Obviously you'll have to adjust your selectors for your use case, but Here's a pen 显然,您必须针对用例调整选择器,但这是一支笔

Here's a GitHub Gist pointing to some examples I created on JSFiddle based off of your specific use case (Stack Overflow doesn't let me post links to JSFiddle directly without including code here, but it's easier to follow along/experiment entirely in JSFiddle): 这是一个GitHub Gist,它指出了我根据您的特定用例在JSFiddle上创建的一些示例(Stack Overflow不允许我在不包含代码的情况下直接发布指向JSFiddle的链接,但是在JSFiddle中完全进行/体验更容易):

https://gist.github.com/andresn/f100386f06ee28e35bd83c62d9219890 https://gist.github.com/andresn/f100386f06ee28e35bd83c62d9219890

More advanced stuff: 更高级的东西:

Ideally, you'd use what's called event delegation instead of adding an onclick to every anchor (DRY = Don't Repeat Yourself is good to always keep in mind while programming and so is KISS = Keep It Simple Silly). 理想情况下,您应该使用所谓的事件委托,而不是在每个锚点上添加onclick(DRY =请勿重复自己是很好的做法,在编程时始终牢记,KISS = Keep It Simple Silly)。 Here is a resource explaining event delegation: https://davidwalsh.name/event-delegate 这是解释事件委托的资源: https : //davidwalsh.name/event-delegate

You can even take this further by preloading all your images so they load behind the scenes when the user first loads the page: https://perishablepress.com/3-ways-preload-images-css-javascript-ajax/ 您甚至可以通过预加载所有图像来进一步做到这一点,以便在用户首次加载页面时将它们加载到幕后: https : //perishablepress.com/3-ways-preload-images-css-javascript-ajax/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM