jquery 切换按钮和文本:工作正常,但希望简化代码,因为它太长太冗长

o0lyfsai  于 2023-08-04  发布在  jQuery
关注(0)|答案(3)|浏览(89)

我有一些盒子里面有很多信息。一开始我想要的信息不多,如果用户想要阅读更多信息,他们就点击按钮“查看更多”。然后,如果他们点击该按钮,将显示名为“复制”的按钮,并通过innerHTML将名为“查看更多”的按钮更改为“查看更少”。
下面的代码工作正常,但有很多代码。有没有可能使代码更短?

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Page title</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

    <div class="wrapper">

<div class="box">

    <div class="content">

<p>This Is a Content Example</p>

    </div>

    <div class="BTN">

<button class="SM">See More</button>

<button class="Copy">Copy</button>

    </div>

</div>

<div class="box">

    <div class="content">

<p>This Is a Content Example</p>

    </div>

    <div class="BTN">

<button class="SM">See More</button>

<button class="Copy">Copy</button>

    </div>

</div>

<div class="box">

    <div class="content">

<p>This Is a Content Example</p>

    </div>

    <div class="BTN">

<button class="SM">See More</button>

<button class="Copy">Copy</button>

    </div>

</div>

    </div>

</body>

</html>

<style>

*{

margin: 0;

padding: 0;

outline: none;

}

body{

    width: 100%;

    height: 100vh;

    display: flex;

    justify-content: center;

    align-items: center;

}

.wrapper{

    width: 90%;

    display: flex;

    flex-direction: column;

}

.box{    

    height: 180px;

    background: blue;

    width: 100%;

    margin-top: 10px;

}

.content{

    height: 100%;

    width: 100%;

    display: flex;

    justify-content: center;

    align-items: center;

}

.content p{

    font-size: 22px;

    color: white;

    font-weight: bold;

}

.BTN{

    position: relative;

    width: 90%;

    margin: auto;

    display: flex;

    justify-content: space-between;

    gap: 8px;

    height: 32px;

    margin-top: -37px;

}

.BTN button{

    height: 100%;

    width: 100%;

    font-size: 18px;

    background: yellow;

    color: red;

    font-weight: bold;

    border: none;

    border-radius: 5px;

}

.Copy{

    display: none;

}

@media(min-width: 600px){

.wrapper{

    flex-direction: row;

    gap: 10px;

}

}

</style>

<script>

var a = document.getElementsByClassName("SM");

var b = document.getElementsByClassName("Copy");

a[0].addEventListener("click", function(){

    if(a[0].innerHTML == "See Less"){

    a[0].innerHTML = "See More";

    b[0].style.display = "None";    

    }else{

    a[0].innerHTML = "See Less";

    b[0].style.display = "block";

    }

});

a[1].addEventListener("click", function(){

    if(a[1].innerHTML == "See Less"){

    a[1].innerHTML = "See More";

    b[1].style.display = "None";    

    }else{

    a[1].innerHTML = "See Less";

    b[1].style.display = "block";

    }

});

a[2].addEventListener("click", function(){

    if(a[2].innerHTML == "See Less"){

    a[2].innerHTML = "See More";

    b[2].style.display = "None";    

    }else{

    a[2].innerHTML = "See Less";

    b[2].style.display = "block";

    }

});

b[0].addEventListener("click", function(){

    alert("You Copied the First Info");

    /* Please Dont Create a Code To Copy because I already know and this is a sample. But if there's a possibility to make this code shorter, please include this.*/

});

b[1].addEventListener("click", function(){

    alert("You Copied the Second Info");

});

b[2].addEventListener("click", function(){

    alert("You Copied the Third Info");

});

</script>

字符串
无论如何,如果有可能在JQuery中缩短代码,那么我想接受它。先谢谢你了

vql8enpb

vql8enpb1#

在您的原始帖子中,您需要解决方案的两个部分:第一个是缩短/简化整个代码,第二个是利用JQuery来实现这一点。
我们可以跳过使用直接功能来编辑和读取DOM(即innerHTML和getElementsByClassName),因为我们可以使用jQuery来处理单击事件并动态更新每个框的内容。
首先,我们将对标记和样式进行如下压缩:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Page title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="wrapper"></div>
</body>
</html>
<style>
    /* Your CSS styles here */
</style>

字符串
请注意,我们只有一个带有“wrapper”类的div。我们将以此为起点来生成框内容。
接下来,我们将更新脚本,以便使用jQuery生成内容,并启用所有必要的功能。请注意,确保包含最新版本的jQuery库。

<script src="https://code.jquery.com/jquery-*.*.*.min.js"></script>
<script>
    // Array containing the content for each box
    const boxContents = [
        'This is the first box content',
        'This is the second box content',
        'This is the third box content'
    ];

    // Function to toggle content visibility and button text
    function toggleContent(index) {
        const boxContent = $('.content p').eq(index);
        const seeMoreBtn = $('.SM').eq(index);
        const copyBtn = $('.Copy').eq(index);

        if (seeMoreBtn.text() === 'See More') {
            boxContent.text(boxContents[index]);
            seeMoreBtn.text('See Less');
            copyBtn.show();
        } else {
            boxContent.text('This Is a Content Example');
            seeMoreBtn.text('See More');
            copyBtn.hide();
        }
    }

    // Click event for "See More" buttons
    $('.wrapper').on('click', '.SM', function () {
        const index = $('.SM').index(this);
        toggleContent(index);
    });

    // Click event for "Copy" buttons
    $('.wrapper').on('click', '.Copy', function () {
        const index = $('.Copy').index(this);
        alert(`${index + 1}`);
        // Copy functionality can continue here
    });

    // Function to generate the dynamic markup for boxes
    function generateBoxes() {
        const wrapper = $('.wrapper');

        // Iterate through boxContents array and create the markup for each box
        for (let i = 0; i < boxContents.length; i++) {
            const boxMarkup = `
                <div class="box">
                    <div class="content">
                        <p>This Is a Content Example</p>
                    </div>
                    <div class="BTN">
                        <button class="SM">See More</button>
                        <button class="Copy">Copy</button>
                    </div>
                </div>
            `;
            wrapper.append(boxMarkup);
        }
    }

    // When the document is ready, generate the boxes and enable the functionality
    $(document).ready(function () {
        generateBoxes();
    });
</script>


由于最初的帖子包含三个框,我们创建了一个名为boxContents的常量,它包含每个框的值。当您单击“查看更多”按钮时,将显示此值。当文档第一次加载时,jQuery将触发generateBoxes函数,该函数将遍历boxContents提供的数组。这将为我们生成必要的HTML,而不需要为每个单独的框手动添加它。
现在我们已经有了我们的盒子,我们需要为按钮创建两个事件。这也可以在jQuery中完成。请注意,在脚本中,我们需要使用.wrapper作为引用的起点。这是因为我们是在DOM加载后为这些框生成html的。如果我们尝试让.SM和.Copy成为这样的直接引用:

$('.SM').on('click', function () {});


则代码将不会运行。在我们的两个事件函数中,我们跟踪按钮的索引。该索引基于boxContents的相关值。对于“查看更多”按钮,它将触发toggleContent函数,该函数会将boxContents中的值添加到相关框中。
注意:在此场景中,您的css将保持不变。

jogvjijk

jogvjijk2#

数组forEach可以提供帮助
[...a]a创建数组
.forEach((el, i)为相应的b提供了一个索引(i),您可以使用el而不是a[i]-这取决于您的实际情况

const a = document.getElementsByClassName("SM");
const b = document.getElementsByClassName("Copy");
[...a].forEach((el, i) => a.addEventListener('click', function () {
    if (el.innerHTML == "See Less") {
        el.innerHTML = "See More";
        b[i].style.display = "None";
    } else {
        el.innerHTML = "See Less";
        b[i].style.display = "block";
    }
}));
[...b].forEach((el, i) => b.addEventListener("click", function () {
    alert(`You copied ${['First', 'Second', 'Third'][i]} Info`);
}));

字符串

x7yiwoj4

x7yiwoj43#

你可以通过jquery用非常简单的代码实现同样的功能。
工作实施例:

$('.SM').click(function() {
  $(this).next('.Copy').toggle(); // hide show copy button
  //code to change button text
  $(this).text(function(i, text){
      return text === "See More" ? "See less" : "See More";
  })
});
* {
  margin: 0;
  padding: 0;
  outline: none;
}

body {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper {
  width: 90%;
  display: flex;
  flex-direction: column;
}

.box {
  height: 180px;
  background: blue;
  width: 100%;
  margin-top: 10px;
}

.content {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content p {
  font-size: 22px;
  color: white;
  font-weight: bold;
}

.BTN {
  position: relative;
  width: 90%;
  margin: auto;
  display: flex;
  justify-content: space-between;
  gap: 8px;
  height: 32px;
  margin-top: -37px;
}

.BTN button {
  height: 100%;
  width: 100%;
  font-size: 18px;
  background: yellow;
  color: red;
  font-weight: bold;
  border: none;
  border-radius: 5px;
}

.Copy {
  display: none;
}

@media(min-width: 600px) {
  .wrapper {
    flex-direction: row;
    gap: 10px;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>

<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Page title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <div class="wrapper">
    <div class="box">
      <div class="content">
        <p>This Is a Content Example</p>
      </div>
      <div class="BTN">
        <button class="SM">See More</button>
        <button class="Copy">Copy</button>
      </div>
    </div>
    <div class="box">
      <div class="content">
        <p>This Is a Content Example</p>
      </div>
      <div class="BTN">
        <button class="SM">See More</button>
        <button class="Copy">Copy</button>
      </div>
    </div>
    <div class="box">
      <div class="content">
        <p>This Is a Content Example</p>
      </div>
      <div class="BTN">
        <button class="SM">See More</button>
        <button class="Copy">Copy</button>
      </div>
    </div>
  </div>
</body>

</html>

注意:请确保您的页面中包含jQuery库,否则此代码将无法工作。

相关问题