admin管理员组

文章数量:1357387

I have a javascript function where i return a html code. In that piece of return statement i want to use if conditions. Please guide me how to use that.

This is my javascript function:

function abc(param)
{
  var step =2;
  if(n>0){

    return `
        <div>
        **{% if step == '1' %}
          <div class="box" style="background-color:red" id="prodcolor">
           <span style="display:none"> Sample</span>
          </div>
        {% endif %}**
        </div>
    `;

  }
}

I have highlighted the place where i have used if statement. This is my javascript file.

I have a javascript function where i return a html code. In that piece of return statement i want to use if conditions. Please guide me how to use that.

This is my javascript function:

function abc(param)
{
  var step =2;
  if(n>0){

    return `
        <div>
        **{% if step == '1' %}
          <div class="box" style="background-color:red" id="prodcolor">
           <span style="display:none"> Sample</span>
          </div>
        {% endif %}**
        </div>
    `;

  }
}

I have highlighted the place where i have used if statement. This is my javascript file.

Share Improve this question edited Mar 14, 2019 at 5:43 asked Mar 14, 2019 at 5:42 user10893802user10893802
Add a ment  | 

2 Answers 2

Reset to default 2

Use different strings for different conditions:

function abc(param)
{
  var step =2;
  if(n>0){

    return step == '1' ? `
        <div>
          <div class="box" style="background-color:red" id="prodcolor">
           <span style="display:none"> Sample</span>
          </div>
        </div>
    `:"<div></div>"

  }
}

You can use string concatenation. Btw, I'm assuming n is global variable here somewhere.

var n = 1

function abc(param)
{
  var step = 2;
  var innerHtml = '';
  if(n>0){
    if (step == '1') {
      innerHtml = `
          <div class="box" style="background-color:red" id="prodcolor">
           <span style="display:none"> Sample</span>
          </div>
      `;
    }
    return `
        <div>
        ${innerHtml}
        </div>
    `;

  }
}

本文标签: How to return html code in a javascript function with conditional statementsStack Overflow