Получить идентификатор и установить его как условие на IF для загрузки Progress-Bar - PullRequest
0 голосов
/ 23 апреля 2019

Окей, моя проблема здесь ... Получил ProgressBar и хочу, чтобы он загрузился. Теперь я достиг этого после того, как пришел с идеей, почему бы мне не взять идентификатор из HTML и поместить его в качестве УСЛОВИЯ в оператор IF для загрузки бара.

Я уже неделю бьюсь над тем, как это сделать, но безуспешно ... есть что-то, чего я не вижу ... что-то, но пока не могу достичь. Его 2 месяца на Javascript, так что не много PhD фразу :)

Я пробовал с getAtribute, .value из некоторого идентификатора с циклом for, но это просто из-за размышлений. Некоторый массив [i] должен быть в состоянии сделать это. Или же?

<div class="progress">
  <div class="progress-bar" id="html" role="progressbar" style="width: 0%;">0/10</div>
</div>
<br><br>
CSS
<div class="progress">
  <div class="progress-bar" id="css" role="progressbar" style="width: 0%;" >0/10</div>
</div>
<br><br>
Javascript
<div class="progress">
  <div class="progress-bar" id="javascript" role="progressbar" style="width: 0%;">0/10</div>
</div>
<br><br>
Visual Studio
<div class="progress">
  <div class="progress-bar" id="visual_st" role="progressbar" style="width: 0%;">6/10</div>
</div>
<br><br>
SQL
<div class="progress">
  <div class="progress-bar" id="sql" role="progressbar" style="width: 0%;">7/10</div>
</div>
</div>
</div>
// this javascript works 
function () {
  var bar = document.getElementsByClassName("progress-bar");         
  if (bar.width() >= 500) {
    clearInterval(progress);
  } else {
    bar.width(bar.width() + 100);
  }
}

и теперь часть, которую я не могу сделать, теперь я пробовал оператор switch.

function () {
  var bar = document.getElementsByClassName("progress-bar");
  var x = document.getElementsByClassName("progress-bar")[a].getAttribute("id");

  switch (x[a]){
    case 'html':
      if (bar.width() >= 500) {
        clearInterval(progress);
      } else {
        bar.width(bar.width() + 100);
      }
      break;
    default:
      break;
  }
}

Ответы [ 2 ]

0 голосов
/ 23 апреля 2019
function pipi(type) {
    switch (type) {
        case 'html':
            var bar = $('#html');

            if ($(bar).width() >= 500) {
                clearInterval(progress);
            } else {
                $(bar).width(bar.width() + 100);
            }
            break;

         default:
         break;
   }
}

pipi('html')
0 голосов
/ 23 апреля 2019

Давайте укажем несколько вещей, так как это поможет вам лучше понять некоторые ключевые проблемы с вашим кодом:

function () { // no function name

  var bar = document.getElementsByClassName("progress-bar"); 
  // 'bar' is a generic term, alonside 'foo', might want to use something like 'progressBar'
  // also, document.getElementsByClassName() returns a HTML Collection - somewhat like an array
  // bar.width() will not work, as you are not applying it to an element, but to an array

  var x = document.getElementsByClassName("progress-bar")[a].getAttribute("id");
  // 'a' is not defined - it shouldbe an index of some sort
  // if it were to work it would return a string - the value of the id itself
  // the id is not meant to be used as such - better use a 'data-attribute' instead

  switch (x[a]){ 
  // x is a string, as mentioned above
  // x[index] will return the letter within the string, at that index;
  // example: 'mystring'[3] - will give you 't', the 4th letter
  // the same result is for: var z ='mystring'; z[3] - will give you 't', the 4th letter
  // x[a] will never return 'html' - as it is a single letter

    case 'html':
    // this will never run - as x[a] returns a single letter/digit 
    // you cannot write 'HTML' with only one letter/digit :)

      // as mentioned above, bar is a HTML Collection, not an element - bar.width() will not work
      if (bar.width() >= 500) {
        clearInterval(progress); 
        // progress is not defined within your posted code, just saying for future posts 
      } else {
        bar.width(bar.width() + 100);
      }
      break;

      // Also, a micro-optimization: you are getting bar.width() twice
      // store it and use the stored value instead of checking it again, just to get the same result

      // long story short, you could change it with :
      // var currentWidth = bar.width();
      // if (currentWidth >= 500) {
      //   clearInterval(progress);
      // } else {
      //   bar.width(currentWidth + 100);
      // }
      // break;

    default:
      // as there is only one case (if x[a]==='html') - which never runs, then the 'default' will always run
      // the 'default' has no code within it - so it will always run .. no code
      break;
  }
};

Ближе к рабочей функции будет:

function (myIndex) {
  var allProgressBars = document.getElementsByClassName("progress-bar");
  var targetProgressBar = allProgressBars[myIndex];
  var targetIdValue = targetProgressBar.getAttribute("id");
  var currentWidth = targetProgressBar.width();

  switch (targetIdValue){

    case 'html':
      if (currentWidth >= 500) {
        clearInterval(progress); // still need to define 'progress' 
      } else {
        bar.width(currentWidth + 100);
      }
      break;

    default:
      break;
  }
};

Ближе к рабочей функции + еще лучше:

Изменение:

<div class="progress-bar" id="html" ...>

Кому:

<div class="progress-bar" data-value="html" ...>

function (myIndex) {
  var allProgressBars = document.getElementsByClassName("progress-bar");
  var targetProgressBar = allProgressBars[myIndex];
  var targetValue = targetProgressBar.getAttribute("data-value");
  var currentWidth = targetProgressBar.width();

  switch (targetValue){

    case 'html':
      if (currentWidth >= 500) {
        clearInterval(progress); // still need to define 'progress' 
      } else {
        bar.width(currentWidth + 100);
      }
      break;

    default:
      break;
  }
};

Удачи!:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...