JavaScript: обрабатывать функции onclick, onmouseover и onmouseout ТОЛЬКО во внешнем файле JavaScript

Поэтому мне приходится отображать простые всплывающие подсказки в различных ситуациях. Мне приходится иметь дело с отменой поведения URL-ссылок по умолчанию с использованием события onclick, показывать всплывающую подсказку при наведении курсора мыши и скрывать всплывающую подсказку при событии mouseout. Я собираюсь включить весь мой код HTML, CSS и JavaScript. Это должно быть сделано только во внешнем файле JavaScript (т.е. вообще нельзя изменить HTML или CSS). Я также не могу использовать innerHTML (должен использовать лучшие практики JavaScript). Я пытался написать код в меру своих возможностей (я действительно новичок в JavaScript). На данный момент ни одна из функций не работает. У меня должно быть ровно 3 функции, и они правильно расположены (я думаю) в Javascript. Ладно, хватит болтать, вот код:

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tool Tips</title>
<link href="css.css" rel="stylesheet" type="text/css" />
<script src="js.js" type="text/javascript"></script>
</head>

<body>
<h1>Tool Tips
</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.

<a href="http://en.wikipedia.org/wiki/Randy_Rhoads" class="tip">Randy Rhoads
<span> Randy Rhoads blah blah blah</span></a> 
ut augue risus.
<a href="http://en.wikipedia.org/wiki/Ty_Tabor" class="tip">Ty Tabor
<span> Ty Tabor blah blah blah</span></a> 
cras pharetra. 
<a href="http://en.wikipedia.org/wiki/Andy_Timmons" class="tip">Andy Timmons
<span> Andy Timmons blah blah blah</span></a> proin mattis, s auctor. 
<a href="http://en.wikipedia.org/wiki/Joe_Bonamassa" class="tip">Joe Bonamassa
<span> Joe Bonamassa blah blah blah</span></a> Duis ac est quam.</p>
</body>
</html>

CSS

/* styles the anchors that have tooltips*/
.tip {
    font-weight: bold;
    border-bottom: 1px dotted #333;
    cursor: help;
    position: relative;
    color: #600;
}

/* hides all tooltips by default on page load */
.tip span {
    display: none;
/* none of these matter now because the tooltips are hidden */
/* when JS unhides the tooltips, these will already be in place */
    position: absolute;
    top: 1.5em;
    left: 0;
    background: #fff;
    border: 1px solid #333;
    width: 100px;
    padding: 5px;
    color: #333;
}

/* applied by JS to show tips */
.tip span.showTip {
    display: block;
}

/* applied by JS to hide tips */
.tip span.hideTip {
    display: none;
}

JavaScript

// *** Use JavaScript best practices ***
// *** This means that the HTML and the CSS are not to be edited at all ***
// *** No <script> tags are to be added to the HTML ***
// *** No inline JavaScript is to be added to the HTML ***
// *** The CSS is to be left alone, no changes are allowed ***

// Step 1: Create the ONLOAD event so that the function prepareTips() runs once the page has finished loading
window.onload = prepareTips;

// Step 2: Declare the prepareTips() function
function prepareTips() {

    // Step 3: Scan the document looking for all anchor tags
    var arrAnchors = document.getElementsByTagName('a');

    // Step 4: Handle browsers that DON'T SUPPORT EITHER CSS OR JAVASCRIPT. 
    // *** If this is the case, the tooltips are hidden and the links open to the Wikipedia pages ***
    if(!document.getElementsByTagName) return false;

    //*** If the browser supports both CSS and JavaScript, the prepareTips() function does the following: ***

    // Step 5: Loop thru all the anchor tags and assigning the events to be handled for all of the links/tooltips
    for (var i=0; i<arrAnchors.length; i++) {

        // Step 6: Bind the showTip() function to the <span> tags' MOUSEOVER event
         arrAnchors.onmouseover = showTip;

        // Step 7: Bind the hideTip() function to the <span> tags' MOUSEOUT event
         arrAnchors.onmouseout = hideTip;

        // Step 8: Bind the showTip() function to the onclick event
        arrAnchors.onclick = showTip;
     }          
}

// *** NOTE: Tooltip triggers are anchor tags and contain the class "tip" ***
// *** NOTE: The .tip class is applied without the use of JavaScript ***
// *** NOTE: The .tip span class formats the tooltip spans but hides them by default.  This is applied without JavaScript ***

// Step 9: Create a separate function called showtip()
function showTip() {

    // Step 10: When an onclick event for a link happens, cancel the default behavior of the link.
    // *** The browser does not go to the URL value contained in the HREF ***
    // *** So the links do nothing when clicked (i.e. return false) instead of going to the Wikipedia page of the guitar player ***
      var arrLinks = document.getElementsByTagName('a');

          for (var i=0; i<arrLinks.length; i++) {
            arrLinks[i].onlick = function() {
            return false;
        }

    // Step 11: The showtip() function changes the anchor class to ".tip span.showTip" located in the CSS file 
    // *** The .tip span.showTip class in the CSS file simply overrides the display property, showing the tooltip span as a block element ***
    // *** This is to be applied using JavaScript (no other properties of the .tip span.showTip will be changed) ***
          arrLinks[i].className === 'showTip';

    // Step 12: Show the associated tooltip when an onmouseover event for a link occurs
    // *** The tooltip that is displayed is the text between the <span>Tooltip text here</span> tags ***
    // *** For example: The tooltip to be displayed when the mouse is hovered over the Randy Rhoads link is: "Randy Rhoads blah blah blah" ***
    // *** The <span> is a child of the anchor (<a>) tags ***
    // *** This means they can be accessed in CSS with a descendant selector .tip span ***
          var tooltip = arrLinks[i].setAttribute('title', arrLinks[i].childName['span'].nodeValue);
     }
}

// Step 13: Create a separate function called hideTip()
function hideTip() {

    // Step 14: The showtip() function changes the anchor class to ".tip span.hideTip" located in the CSS file 
    // *** The .tip span.hideTip class in the CSS file sets the display property back to none, hiding the tooltip ***
      var hideTips = document.getElementsByTagName('a');

    // Step 15: Hide the associated tooltip when the mouseout event for the links occurs.
    // *** The <span> is a child of the anchor (<a>) tags ***
    // *** This means they can be accessed in CSS with a descendant selector .tip span ***
      hideTips[i].className === 'hideTip';
}

person HoppedUpDesigns    schedule 07.10.2012    source источник
comment
Это реальный код JavaScript? Звездочки * делают синтаксис недействительным. Кроме того, === — это оператор сравнения, а не оператор присваивания. Более того, опубликуйте сообщение об ошибке, которое вы получаете при запуске кода (проверьте консоль ошибок JavaScript вашего браузера).   -  person Zeta    schedule 07.10.2012
comment
Извините, дополнительные звезды были добавлены, когда я выделил текст жирным шрифтом с помощью текстового редактора. Единственное сообщение об ошибке, которое я получаю: TypeError: функция prepareTips не всегда возвращает значение Я думаю, что здесь много неправильного кода, но я не уверен, как исправить эти ошибки.   -  person HoppedUpDesigns    schedule 07.10.2012
comment
Я не понимаю, что кто-то хочет снова изобрести велосипед. Когда вы гуглите решения всплывающей подсказки javascript, вы найдете то, что хотите. Кроме того, попробуйте использовать jQuery, это сделает вашу жизнь проще, и для него доступно достаточно плагинов.   -  person Codebeat    schedule 07.10.2012
comment
Пока не могу использовать jQuery... это для класса... мы не изучали jQuery... Я полный новичок   -  person HoppedUpDesigns    schedule 07.10.2012


Ответы (3)


Бегло взглянув, можно предположить, что ваша проблема заключается в том, что вы return false когда браузер не может использовать JS/CSS, но не return true когда он это делает. Это приводит к проблеме, с которой вы столкнулись. Я предполагаю, что вы должны что-то сделать (и не только return false), когда он не может обрабатывать JS/CSS, но вы пытались вернуться в качестве заполнителя.

Примечание: если браузер не поддерживает JS... как он должен выполнять JS, чтобы определить, поддерживает он его или нет?

person Rhyono    schedule 07.10.2012
comment
Очень хорошие моменты :) Все, что я знаю, это то, что в классе мой учитель говорит поставить if(!document.getElementByID) или что-то в этом роде и вернуть false. Это единственный способ, который я знаю - person HoppedUpDesigns; 07.10.2012
comment
@HoppedUpDesigns Ваш учитель, скорее всего, невежественный новичок, способный делать только то, что указано в книге, написанной таким же автором-любителем. Вам просто нужно будет делать то, что я делал в колледже: делать так, как вам показывают в классе, а затем делать это правильно, работая над собственными проектами. - person Rhyono; 08.10.2012

Я предполагаю, что вы говорите о выводе текста во всплывающую подсказку из текста диапазона, и вы не вводите текст в диапазон для отображения во всплывающей подсказке тега привязки. Вы не получаете текст span в строке заголовка, и вы даже не упомянули функцию должным образом в своей функции загрузки. Вы получите лучшее представление о своих небольших ошибках и исправлениях в приведенном ниже коде. Прокомментируйте свой код js и поместите этот код js.

// *** Use JavaScript best practices ***
// *** This means that the HTML and the CSS are not to be edited at all ***
// *** No <script> tags are to be added to the HTML ***
// *** No inline JavaScript is to be added to the HTML ***
// *** The CSS is to be left alone, no changes are allowed ***

// Step 1: Create the ONLOAD event so that the function prepareTips() runs once the page has finished loading
window.onload = prepareTips;

// Step 2: Declare the prepareTips() function
function prepareTips() {

    // Step 3: Scan the document looking for all anchor tags
    var arrAnchors = document.getElementsByTagName('a');

    // Step 4: Handle browsers that DON'T SUPPORT EITHER CSS OR JAVASCRIPT. 
    // *** If this is the case, the tooltips are hidden and the links open to the Wikipedia pages ***
    if(!document.getElementsByTagName) return false;

    //*** If the browser supports both CSS and JavaScript, the prepareTips() function does the following: ***

    // Step 5: Loop thru all the anchor tags and assigning the events to be handled for all of the links/tooltips
    for (var i=0; i<arrAnchors.length; i++) {

        // Step 6: Bind the showTip() function to the <span> tags' MOUSEOVER event
         arrAnchors.onmouseover = showTip();

        // Step 7: Bind the hideTip() function to the <span> tags' MOUSEOUT event
         arrAnchors.onmouseout = hideTip();

        // Step 8: Bind the showTip() function to the onclick event
        arrAnchors.onclick = showTip();
     }          
}

// *** NOTE: Tooltip triggers are anchor tags and contain the class "tip" ***
// *** NOTE: The .tip class is applied without the use of JavaScript ***
// *** NOTE: The .tip span class formats the tooltip spans but hides them by default.  This is applied without JavaScript ***

// Step 9: Create a separate function called showtip()
function showTip() {

    // Step 10: When an onclick event for a link happens, cancel the default behavior of the link.
    // *** The browser does not go to the URL value contained in the HREF ***
    // *** So the links do nothing when clicked (i.e. return false) instead of going to the Wikipedia page of the guitar player ***
      var arrLinks = document.getElementsByTagName('a');

          for (var i=0; i<arrLinks.length; i++) {
            arrLinks[i].onlick = function() {
            return false;
        }

    // Step 11: The showtip() function changes the anchor class to ".tip span.showTip" located in the CSS file 
    // *** The .tip span.showTip class in the CSS file simply overrides the display property, showing the tooltip span as a block element ***
    // *** This is to be applied using JavaScript (no other properties of the .tip span.showTip will be changed) ***
          arrLinks[i].className === 'showTip';

    // Step 12: Show the associated tooltip when an onmouseover event for a link occurs
    // *** The tooltip that is displayed is the text between the <span>Tooltip text here</span> tags ***
    // *** For example: The tooltip to be displayed when the mouse is hovered over the Randy Rhoads link is: "Randy Rhoads blah blah blah" ***
    // *** The <span> is a child of the anchor (<a>) tags ***
    // *** This means they can be accessed in CSS with a descendant selector .tip span ***
          arrLinks[i].setAttribute('title', arrLinks[i].childNodes[1].innerHTML);
     }
}

// Step 13: Create a separate function called hideTip()
function hideTip() {

    // Step 14: The showtip() function changes the anchor class to ".tip span.hideTip" located in the CSS file 
    // *** The .tip span.hideTip class in the CSS file sets the display property back to none, hiding the tooltip ***
      var hideTips = document.getElementsByTagName('a');

    // Step 15: Hide the associated tooltip when the mouseout event for the links occurs.
    // *** The <span> is a child of the anchor (<a>) tags ***
    // *** This means they can be accessed in CSS with a descendant selector .tip span ***
      hideTips[i].className === 'hideTip';
person Dhaval    schedule 07.10.2012

Почему вы используете «css» и «javascript», чтобы показать всплывающую подсказку и скрыть всплывающую подсказку. Это очень простой способ отобразить всплывающую подсказку по URL-адресу в HTML. Просто измените несколько строк в вашем коде, который я написал ниже. Вам не нужно использовать css и javascript.

<a href="http://en.wikipedia.org/wiki/Randy_Rhoads" title="go to randy rhoad wikipedia  page">Randy Rhoads
<a href="http://en.wikipedia.org/wiki/Ty_Tabor" title="go to Tv Tabor wikipedia page">Ty Tabor
<a href="http://en.wikipedia.org/wiki/Andy_Timmons" title="go to Andy Timmons wikipedia page">Andy Timmons
<a href="http://en.wikipedia.org/wiki/Joe_Bonamassa" title="go to Joe Bonamassa wikipedia page">Joe Bonamassa
person vinus patel    schedule 07.10.2012
comment
Я вообще не могу изменить HTML или CSS (см. комментарии вверху кода Javascript). Все должно быть сделано во внешнем файле Javascript. - person HoppedUpDesigns; 07.10.2012